openssl_encrypt returns false

dasj19 picture dasj19 · Jan 31, 2017 · Viewed 8.5k times · Source

I am trying to encrypt a string using openssl_encrypt in PHP but it keeps returning FALSE.

$encrypted = openssl_encrypt('1234', 'AES-256-CBC', 'kGJeGF2hEQ', OPENSSL_ZERO_PADDING, '1234123412341234');

What am I doing wrong?

Answer

Mjh picture Mjh · Jan 31, 2017

On top of answers posted, which are excellent, the code you're after, given your input parameters would be the following:

$plaintext = '1234';
$cipher = 'AES-256-CBC';
$key = 'this is a bad key';
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher));

$encrypted = openssl_encrypt($plaintext, $cipher, $key, 0, $iv);

if(false === $encrypted)
{
    echo openssl_error_string();
    die;
}

$decrypted = openssl_decrypt($encrypted, $cipher, $key, 0, $iv);

$result = $decrypted === $plaintext;

print $result ? 'Everything is fine' : 'Well, we did not decrypt good, did we?';

Having written the above, I advise against using it and instead, please use a tested library designed to handle the complexities of encryption and decryption for you.

I suggest using defuse/php-encryption