Reputation: 2348
I have taken reference of code from this post : Trying to decrypt with aes-256-gcm with php
Code :
< ?php
$textToEncrypt = "demo text";
$password = '3sc3RLrpd17';
$key = substr(hash('sha256', $password, true), 0, 32);
$cipher = 'aes-256-gcm';
$iv_len = openssl_cipher_iv_length($cipher);
$tag_length = 16;
$iv = openssl_random_pseudo_bytes($iv_len);
$ciphertext = openssl_encrypt($textToEncrypt, $cipher, $key, OPENSSL_RAW_DATA, $iv);
$encrypted = base64_encode($iv.$ciphertext);
$textToDecrypt = $encrypted;
$encrypted = base64_decode($textToDecrypt);
$password = '3sc3RLrpd17';
$key = substr(hash('sha256', $password, true), 0, 32);
$cipher = 'aes-256-gcm';
$iv_len = openssl_cipher_iv_length($cipher);
$iv = substr($encrypted, 0, $iv_len);
$ciphertext = substr($encrypted, $iv_len);
$decrypted = openssl_decrypt($ciphertext, $cipher, $key, OPENSSL_RAW_DATA, $iv);
var_dump (openssl_error_string());
var_dump($decrypted);
echo $decrypted;
?>
Running this code on PHP 5.6 Now the issue is I am always getting false as decrypted text.
What is wrong?
Upvotes: 0
Views: 751
Reputation: 31
I got this working with AES-256-CBC on PHP 5.6:
$textToEncrypt = "demo text";
$password = '3sc3RLrpd17';
$key = substr(hash('sha256', $password, true), 0, 32);
$cipher = 'aes-256-cbc';
$iv_len = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($iv_len);
$ciphertext = openssl_encrypt($textToEncrypt, $cipher, $key, OPENSSL_RAW_DATA, $iv);
if ($ciphertext === false) {
// Encryption failed; handle error
echo "Encryption error: " . openssl_error_string() . "\n";
exit;
}
$encrypted = base64_encode($iv . $ciphertext);
// Decryption
$textToDecrypt = $encrypted;
$encrypted = base64_decode($textToDecrypt);
$iv = substr($encrypted, 0, $iv_len);
$ciphertext = substr($encrypted, $iv_len);
$decrypted = openssl_decrypt($ciphertext, $cipher, $key, OPENSSL_RAW_DATA, $iv);
if ($decrypted === false) {
// Decryption failed; handle error
echo "Decryption error: " . openssl_error_string() . "\n";
exit;
}
echo "Decrypted text: " . $decrypted . "\n";
You can see it running here: https://onlinephp.io/c/74e59
Upvotes: 1