Take a look at mcyrpt_encrypt()
:
string mcrypt_encrypt ( string $cipher , string $key , string $data ,
string $mode [, string $iv ] )
Set $cipher
to MCRYPT_RIJNDAEL_128
(AES-128), and $mode
to MCRYPT_MODE_CBC
.
Then use base64_encode()
to generate a base-64 encoded output (ie: what the -a
option
does).
openssl derives the key and IV as follows:
Key = MD5(Password + Salt)
IV = MD5(Key + Password + Salt)
Where Salt
is a 8 byte salt. With this in mind, I created simple encrypt()
and decrypt()
routines:
function ssl_encrypt($pass, $data) {
$salt = substr(md5(mt_rand(), true), 8);
$key = md5($pass . $salt, true);
$iv = md5($key . $pass . $salt, true);
$ct = mcrypt_encrypt (MCRYPT_RIJNDAEL_128, $key, $data,
MCRYPT_MODE_CBC, $iv);
return base64_encode('Salted__' . $salt . $ct);
}
function ssl_decrypt($pass, $data) {
$data = base64_decode($data);
$salt = substr($data, 8, 8);
$ct = substr($data, 16);
$key = md5($pass . $salt, true);
$iv = md5($key . $pass . $salt, true);
$pt = mcrypt_decrypt (MCRYPT_RIJNDAEL_128, $key, $ct,
MCRYPT_MODE_CBC, $iv);
return $pt;
}
The parameter $data
takes the string to be encrypted. If you want to encrypt a file, you'll have to get it via file_get_contents()
or similar and then give that to the function.
Usage:
echo ssl_encrypt('super secret key', 'Hello World');
Generates something like (will change every time because of the random salt):
U2FsdGVkX18uygnq8bZYi6f62FzaeAnyB90U6v+Pyrk=