PHP decryption with mcrypt returns strange text instead of plaintext

I'm just trying to encrypt and decrypt a string. But when I output the decrypted string, I get:

   ^    V  _  n .ZZ  Ǐ  : 2   

My code is:

 function encrypt($string, $secret_key = "ATRTHTRAGSFRSGTS") { $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND); return mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $secret_key, $string, MCRYPT_MODE_CBC, $iv); } function decrypt($string, $secret_key = "ATRTHTRAGSFRSGTS") { $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND); return mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $secret_key, $string, MCRYPT_MODE_CBC, $iv); } $text = 'This is a test.'; $enc = encrypt($text); $dec = decrypt($enc); echo $dec; 

What ideal might be wrong?

+1
php encryption mcrypt
source share
1 answer

You randomly generate an initialization vector (IV) during encryption, which means that the encrypted text will be randomized in accordance with this IV. When you decrypt, you need to provide the same IV that you used for encryption.

Since IV does not have to be secret, you can simply add it to encrypted text or send it in another way. Do not generate another IV during decryption.

If your plaintext was longer (more than 32 bytes), you would see that the first 32 bytes were incorrect, but the rest were correct. If you want to know more about how CBC mode works, Wikipedia got you.


During encryption, mcrypt applies padding of 0x00 bytes to plaintext, because Rijndael in CBC mode runs on blocks of 16 bytes. You need to remove the registration after decryption, because it does not work automatically:

 return rtrim(mcrypt_decrypt(...), "\0"); 

Also, be sure to authenticate your encrypted texts, because otherwise, attacks such as the padding-oracle attack can be used to fully decrypt some encrypted text. Authentication using encrypted text can be performed using an authenticated mode, such as GCM, or with an authentication tag generated through the HMAC pass through the encrypted text.

see also

  • A: How do you encrypt and decrypt a PHP string?
  • A: How to encrypt / decrypt data in php?

In the comments on the question that mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB) should not contain ECB , but rather CBC mode, there was a bit of controversy because ECB mode does not use IV, but mcrypt is bad and it happily returns a valid IV for CBC (32 bytes in this case), despite the request "IV for ECB", which should have been 0 bytes.

mcrypt is a failure and should no longer be used. Use openssl / libsodium / defuse / ...

+5
source share

All Articles