php - 尝试使用 php 使用 aes-256-gcm 解密

标签 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);

加密码
$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));

最佳答案

您需要保存 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.$ciphertext.$tag);
解密:
$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);

关于php - 尝试使用 php 使用 aes-256-gcm 解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52477247/

相关文章:

php - 计算页面上执行的 MySQL 查询数

java - 仅使用java中的密码加密对字符串字符进行加密

node.js - 带 Angular RSA库

java - 我注意到 log4j2.xml 中某些属性前面的前缀 'sd:'——它们代表什么?

java - 找不到任何支持 AES/GCM/NoPadding 的提供商

php - 如何批量更新 Google 表格附加数字而不是字符串/撇号

php - Facebook 图形 API - OAuth token

php - 在 Laravel 中,如何在测试时给服务容器另一种实现?

java - 在 Node js 中通过 AES/GCM/NoPadding 算法使用 key 和 iv 加密有效负载并在 java 中解密

encryption - SonarQube : Make sure that encrypting data is safe here. AES/GCM/NoPadding、RSA/ECB/PKCS1Padding