0

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���삭
0

1 Answer 1

0

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
2
  • Note that IVs are not considered to be secret, and should change for each message that you encrypt. Many crypto libraries simply attach the IV to the ciphertext for transmission/storage, eg: simply prepending the IV to the ciphertext.
    – Sammitch
    Sep 2, 2021 at 18:45
  • Thank you for your help! So I want to encrypt the plaintext in one PHP file and decode it in the other, how should I use random iv?
    – park
    Sep 3, 2021 at 9:29

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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