It's seems that there isn't any pleasant way to encrypt a file in php.
The built in methods of php, mcrypt, aren't very portable as most servers don't support them.
Command line encryption tools are like ugly hacks.
There's encryption for strings which is nice, but if we want to encrypt a file it doesn't help very much especially for someone else to unencrypt it.
Other encryption tools require public keys, key rings, private keys, blood sample... These seem much too complicated for just encrypting a file.
It seems that we should just have a simple function for PHP that could work like so:
$crypt = new Crypt();
$crypt->encryptFile("Password1245!", 'secret_file.txt', 'encrypted_file.txt');
$crypt->decryptFile("Password1245!", 'encrypted_file.txt', 'original_file.txt');
Any one have any ideas? I'm pulling out hair!
EDIT: Another thing I should add, for the end user to be able to decrypt the file with ease.
Basically I'm trying to find something that can replace a password protected zip file
Take a look at the PEAR encryption packages. They don't all rely on mcrypt - for example Crypt_Blowfish.
If you don't mind having the mcrypt extension installed, this code should do it:
function Encrypt($string, $key)
{
if (extension_loaded('mcrypt') === true)
{
return base64_encode(mcrypt_encrypt(MCRYPT_BLOWFISH, substr($key, 0, mcrypt_get_key_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB)), trim($string), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB), MCRYPT_RAND)));
}
return false;
}
function Decrypt($string, $key)
{
if (extension_loaded('mcrypt') === true)
{
return trim(mcrypt_decrypt(MCRYPT_BLOWFISH, substr($key, 0, mcrypt_get_key_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB)), base64_decode($string), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB), MCRYPT_RAND)));
}
return false;
}
function Encrypt_File($source, $destination, $key)
{
if (extension_loaded('mcrypt') === true)
{
if (is_file($source) === true)
{
$source = file_get_contents($source);
if (file_put_contents($destination, Encrypt($source, $key), LOCK_EX) !== false)
{
return true;
}
}
}
return false;
}
function Decrypt_File($source, $destination, $key)
{
if (extension_loaded('mcrypt') === true)
{
if (is_file($source) === true)
{
$source = file_get_contents($source);
if (file_put_contents($destination, Decrypt($source, $key), LOCK_EX) !== false)
{
return true;
}
}
}
return false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With