Trying to decrypt with aes-256-gcm with php

C.lau picture C.lau · Sep 24, 2018 · Viewed 8.6k times · Source

I wondered whether anyone can help,

I am using encryption method aes-256-gcm, I can encrypt, but cannot decrypt.

Below is my code, can anyone see where I'm going wrong

$textToDecrypt = $_POST['message'];
$password = '3sc3RLrpd17';
$method = 'aes-256-gcm'; 
$tag_length = 16;
$password = substr(hash('sha256', $password, true), 0, 32);
$iv = chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0);
$decrypted = openssl_decrypt(base64_decode($textToDecrypt), $method, 
$password, OPENSSL_RAW_DATA, $iv, $tag_length);

Encryption code

$textToEncrypt = $_POST['message'];
$password = '3sc3RLrpd17';
$method = 'aes-256-gcm'; 
$tag_length = 16;


$password = substr(hash('sha256', $password, true), 0, 32);



$iv = chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . 
chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . 
chr(0x0) . chr(0x0) . chr(0x0);


$encrypted = base64_encode(openssl_encrypt($textToEncrypt, $method, 
$password, OPENSSL_RAW_DATA, $iv, $tag_length));

Answer

rustyx picture rustyx · Sep 25, 2018

You need to save the GCM tag (HMAC) with the ciphertext and pass it to the decryption function. It is not saved for you automatically (you should also generate a good IV and store it with the ciphertext as well).

openssl_encrypt is specified as:

string openssl_encrypt ( string $data , string $method , string $key [, int $options = 0 [, string $iv = "" [, string &$tag = NULL [, string $aad = "" [, int $tag_length = 16 ]]]]] )

If you look closely, you're passing in $tag_length where $tag is expected.

Here's how it should look like:

Encryption:

$textToEncrypt = $_POST['message'];
$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);
$tag = ""; // will be filled by openssl_encrypt

$ciphertext = openssl_encrypt($textToEncrypt, $cipher, $key, OPENSSL_RAW_DATA, $iv, $tag, "", $tag_length);
$encrypted = base64_encode($iv.$ciphertext.$tag);

Decryption:

$textToDecrypt = $_POST['message'];
$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);
$tag_length = 16;
$iv = substr($encrypted, 0, $iv_len);
$ciphertext = substr($encrypted, $iv_len, -$tag_length);
$tag = substr($encrypted, -$tag_length);

$decrypted = openssl_decrypt($ciphertext, $cipher, $key, OPENSSL_RAW_DATA, $iv, $tag);