Search code examples
phpencryptionopensslphp-openssl

PHP openssl_decrypt random_pseudo_bytes error, help me


I succeeded in encrypting the plaintext using PHP openssl, but with openssl_decrypt, I get this error.

�RC(�ɸ�gQ���삭

What is the reason for alien language to float? I think this is the problem:

openssl_random_pseudo_bytes (16). 

openssl_random_pseudo_bytes(opensl_cipher_iv_length ("AES-128-CBC")); is the same situation.

function aes_encode($text, $s_key){
    $iv = openssl_random_pseudo_bytes(16);
    return base64_encode(openssl_encrypt($text, "AES-128-CBC", $s_key, 0, $iv));
  }

  $encrypt_text = aes_encode($plaintext, $s_key);
  echo $encrypt_text;

function aes_decode($encrypt_text, $s_key){
    $iv = openssl_random_pseudo_bytes(16);
    return openssl_decrypt(base64_decode($encrypt_text), "AES-128-CBC", $s_key, 0, $iv);
}

$decrypt_text = aes_decode($encrypt_text, $s_key);
echo $decrypt_text;

<result>
QUxwTUxiSTkwWFc2WE0zcmtSOXNHR0cyKzU1RWIvNkxnaGJTZmdnVlB4VT0=
�RC(�ɸ�gQ���삭

Solution

  • You need to use the same IV you encrypted with when decrypting:

    function aes_encode($text, $s_key, $iv){
        return base64_encode(openssl_encrypt($text, "AES-128-CBC", $s_key, 0, $iv));
    }
    
    function aes_decode($encrypt_text, $s_key, $iv){
        return openssl_decrypt(base64_decode($encrypt_text), "AES-128-CBC", $s_key, 0, $iv);
    }
    $plaintext = 'testtest';
    $s_key = 'secret';
    $iv = openssl_random_pseudo_bytes(16);
    
    $encrypt_text = aes_encode($plaintext, $s_key, $iv);
    echo $encrypt_text;
    
    echo "\n";
    
    $decrypt_text = aes_decode($encrypt_text, $s_key, $iv);
    echo $decrypt_text;
    

    Output

    SVg2Y0FtV1h6RFZac2t5UjhxNDhpdz09
    testtest