шифрование — попытка расшифровать с помощью aes-256-gcm с переполнением стека

Интересно, может ли кто-нибудь помочь,

Я использую метод шифрования aes-256-gcm, я могу зашифровать, но не могу расшифровать.

Ниже мой код, кто-нибудь может увидеть, где я иду не так

$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);

Код шифрования

$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));

1

Решение

Вам нужно сохранить GCM tag (HMAC) с зашифрованным текстом и передайте его функции дешифрования. Он не сохраняется для вас автоматически (вы также должны сгенерировать хороший IV и сохранить его вместе с зашифрованным текстом).

openssl_encrypt указан как:

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

Если вы посмотрите внимательно, вы проходите мимо $tag_length где $tag ожидается.

Вот как это должно выглядеть:

Шифрование:

$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.$tag.$ciphertext);

Дешифрирование:

$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);
$tag = substr($encrypted, $iv_len, $tag_length);
$ciphertext = substr($encrypted, $iv_len + $tag_length);

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

Другие решения

Других решений пока нет …