I've found a pair of encryption and decryption functions that look like they obey all the rules of data security that I'm desperate to fully understand but probably won't be able to without a doctorate in this stuff.
They work great when I'm encrypting and decrypting something on the same page with the same IV.
But when I try saving the results to an SQL database and then pulling them back out again and decrypting, it doesn't work.
$key = "secretsecret";
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_DEV_RANDOM);
function encrypt($key, $text, $iv) {
return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $text, MCRYPT_MODE_CBC, $iv)));
}
function decrypt($key, $text, $iv) {
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($text), MCRYPT_MODE_CBC,$iv));
}
$text = "the text to encrypt";
echo "Plain Text: " . $text . "<br><br>";
$encrypted = encrypt($key, $text, $iv);
echo "Encrypted Text: " . $encrypted . "<br><br>";
echo "Decrypted Text: ". decrypt($key, $encrypted, $iv) . "<br><br>"; //this works fine
//save encrypted text to SQL
mysql_query("UPDATE table SET test='".addslashes($encrypted)."' WHERE id='1'");
Then if on another page view I pull the text back out and try to:
echo "Decrypted Text: ". decrypt($key, $textFromSQL, $iv) . "<br><br>";
I get gibberish. What do I need to do to get the text decrypted properly with a different IV?