Reputation: 45
I need to be able to encrypt and decrypt a variable, however I also need to know if the decryption was successful. In my code, when I change the $string
variable before decryption to something else, I receive random characters.
function encrypt($string) {
$key = 'password';
$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));
return $encrypted;
}
function decrypt($encrypted) {
$key = 'password';
$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($encrypted), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
return $decrypted;
}
$string = 'Hello world.';
if (encrypt($string)) {
$string = encrypt($string);
echo $string;
echo '<br>';
}
if (decrypt($string)) {
$string = decrypt($string);
echo $string;
echo '<br>';
}
Is it possible to detect failed decryption? Thanks.
Upvotes: 2
Views: 1008
Reputation: 93948
The best way to detect tampering of the ciphertext is to add a MAC (message authentication code) over the ciphertext. This is a signature generated by a secret key. The key used for this should be different from the one used to perform the encryption. One way to do this is to use a KDF (key derivation function) over a master key to generate the two keys.
Alternatively it is possible to use an authenticated cipher such as GCM (Galois Counter Mode).
The authentication data generated by the MAC or by the authenticated cipher is called an authentication tag.
A reasonable implementation of what you are trying to achieve seems to be embedded in the Zend framework:
http://www.zimuel.it/en/english-cryptography-made-easy-with-zend-framework/
Don't forget to retrieve and store the salt together with the ciphertext (call getSalt()
after encryption, use setSalt()
during decryption). Note that the author confuses the word salt and IV often, which is not a good sign.
Disclaimer: I haven't read through the symmetric cipher code deployed by this component, and I haven't tested the code in any way.
Upvotes: 2