I found an example for en/decoding strings in PHP. At first it looks very good but it wont work :-(
Does anyone know what the problem is?
$Pass = "Passwort";
$Clear = "Klartext";
$crypted = fnEncrypt($Clear, $Pass);
echo "Encrypted: ".$crypted."</br>";
$newClear = fnDecrypt($crypted, $Pass);
echo "Decrypted: ".$newClear."</br>";
function fnEncrypt($sValue, $sSecretKey) {
return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $sSecretKey, $sDecrypted, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))));
}
function fnDecrypt($sValue, $sSecretKey) {
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $sSecretKey, base64_decode($sEncrypted), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)));
}
The result is:
Encrypted: boKRNTYYNp7AiOvY1CidqsAn9wX4ufz/D9XrpjAOPk8=
Decrypted: —‚(ÑÁ ^ yË~F'¸®Ó–í œð2Á_B‰Â—
If you are using PHP >= 7.2 consider using inbuilt sodium core extension for encrption.
Find more information here -
http://php.net/manual/en/intro.sodium.php
.Few important things to note with AES encryption:
CBC
instead.If you are using MCRYPT_RIJNDAEL_128, try
rtrim($output, "\0\3")
. If the length of the string is less than 16, the decrypt function will return a string with length of 16 characters, adding 03 at the end.You can easily check this, e.g. by trying:
$sDecrypted
and$sEncrypted
were undefined in your code. See a solution that works (but is not secure!):STOP!
But there are other problems in this code which make it insecure, in particular the use of ECB (which is not an encryption mode, only a building block on top of which encryption modes can be defined). See Fab Sa's answer for a quick fix of the worst problems and Scott's answer for how to do this right.
For information
MCRYPT_MODE_ECB
doesn't use the IV (initialization vector). ECB mode divide your message into blocks and each block is encrypted separately. I really don't recommended it.CBC mode use the IV to make each message unique. CBC is recommended and should be used instead of ECB.
Example :
You have to stock the IV to decode each message (IV are not secret). Each message is unique because each message has an unique IV.
I am using thing code for CCAVenue Payment Getway
User of code