2

I'm using

openssl_decrypt($encrypted_content, 'aes-256-cbc', $key, 0, $iv)

I have noticed that when the wrong $key is given, the result is false. php.net says

Return Values: The decrypted string on success or FALSE on failure.

What does success and failure mean? Is it guaranteed that if the wrong key is provided, the function will always return FALSE?

In other words, is it possible that a wrong key be given, and the result be a wrongly decrypted string?

1

This is likely because openssl_encrypt uses PKCS7 padding by default. The FALSE likely occurs when the padding is invalid.

It is possible to get the wrong result of decryption if the padding is kept intact. You should use an authenticated mode like GCM or append an HMAC.

| improve this answer | |
  • Decrypting with wrong key doesn't really 'keep intact' CBC padding, but it has a probability slightly better than 1/256 (0.4%) of producing padding that appears valid, which returns effectively random (garbage) data rather than the error indication. – dave_thompson_085 Nov 3 '16 at 5:29
0

Yes, it is possible that openssl_decrypt returns garbage when the incorrect key is used. Here is a code example where that happens:

<?php
# Encrypt some text.
$iv = "underconsumption";
$key = "secret";
$plaintext = "hello world";
$encrypted_content = openssl_encrypt($plaintext, 'aes-256-cbc', $key, 0, $iv);

# Try decrypting with correct key.
$result = openssl_decrypt($encrypted_content, 'aes-256-cbc', $key, 0, $iv);
echo "Decrypted with correct key: $result\n";

# Using the wrong key sometimes results in garbage.
$key = 'saacua';
$result = openssl_decrypt($encrypted_content, 'aes-256-cbc', $key, 0, $iv);
echo "Decrypted with incorrect key: $result\n";
?>

This prints this:

Decrypted with correct key: hello world
Decrypted with incorrect key: �O�@D�b���k��
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.