尝试使用PHP的AES-256-GCM解密

C.l*_*lau 3 php encryption aes-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);
Run Code Online (Sandbox Code Playgroud)

加密码

$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));
Run Code Online (Sandbox Code Playgroud)

rus*_*tyx 5

您需要将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);
Run Code Online (Sandbox Code Playgroud)

解密:

$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);
Run Code Online (Sandbox Code Playgroud)