Ok, I have tried to create my own encryption/decryption methods using PHP mcrypt
, and when I posted them a while back some called them "trash". They were mentioning things about "Initialization Vectors" and such. Basically, how can I make these cryptography methods better:
function encrypt($key, $data){
$encrypted_data = mcrypt_cbc(MCRYPT_RIJNDAEL_192, $key, $data, MCRYPT_ENCRYPT);
return base64_encode($encrypted_data);
}
function decrypt($key, $encryptedData){
$dec = base64_decode($encryptedData);
$decrypt = mcrypt_cbc(MCRYPT_RIJNDAEL_192, $key, $dec, MCRYPT_DECRYPT);
return trim($decrypt);
}
I want these to work the best they can except I am a duck in a brand new world when it comes to mcrypt
, any suggestions are welcome, thanks!
Here is a snippet of the mcrypt functions I use. They use
mcrypt_generic
andmdecrypt_generic
, which should be used according to the PHP manual.I don't know much about
mcrypt
either, so I just kinda hacked these together. Imd5
the key so it's always 32 characters (the max key length), and I randomly calculate an "Initialization Vector".Using PKCS7 Padding is better because you can have strings that end in white space (as
trim
would remove that), also the encryption is more efficient when the string is a certain length.I'm using AES 256 (MCRYPT_RIJNDAEL_256) here, but AES 192 (MCRYPT_RIJNDAEL_192) would work too.
Demo: http://ideone.com/WA5Tk
You can create an iv with
mcrypt_create_iv()
, using the appropriate size for your encryption mode.Then pass it to
mcrypt_cbc()
as the optional 5th parameter. The only changes I've made here to your original functions are to pass in$iv
: