AES En/Decryption and moving from phpseclib 2 to 3 #1974
-
I used to have the following code for encrypting/decrypting in phpseclib 2: function auth_encrypt($data, $secret)
{
$iv = random_bytes(16);
$cipher = new AES();
$cipher->setPassword($secret);
return $cipher->encrypt($iv . $data);
}
function auth_decrypt($ciphertext, $secret)
{
$iv = substr($ciphertext, 0, 16);
$cipher = new AES();
$cipher->setPassword($secret);
$cipher->setIV($iv);
return $cipher->decrypt(substr($ciphertext, 16));
} When trying to port that code to version 3 I came up with the following: function auth_encrypt($data, $secret)
{
$iv = random_bytes(16);
$cipher = new AES('cbc');
$cipher->setPassword($secret);
$cipher->setIV($iv);
return $cipher->encrypt($iv . $data);
}
function auth_decrypt($ciphertext, $secret)
{
$iv = substr($ciphertext, 0, 16);
$cipher = new AES('cbc');
$cipher->setPassword($secret);
$cipher->setIV($iv);
return $cipher->decrypt(substr($ciphertext, 16));
} The new code works, as far as it is possible to decrypt what has been encrypted with it. However what does not work is decrypting any cipher that has been encrypted with the old version 2 code. The error I receive when trying to decode old ciphers is:
I strongly suspect it's something about the IV handling. I did not write the original code and I am not familiar enough with AES to really understand what's going on. Could anyone help me port the original code into new version 3 compatible code? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
phpseclib v2 null padded the ciphertext. You can simulate it thusly: $len = strlen($ciphertext);
$block_size = $cipher->getBlockLengthInBytes();
$ciphertext = str_pad($ciphertext, $len + ($block_size - $len % $block_size) % $block_size, chr(0)); The fact that your original code is relying on that means that the last few bytes of the original code aren't getting decrypted correctly. |
Beta Was this translation helpful? Give feedback.
-
Try this:
phpseclib v3 changed the salt from |
Beta Was this translation helpful? Give feedback.
Try this:
phpseclib v3 changed the salt from
phpseclib
tophpseclib/salt
.