gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 21:15:09 29 4
gpt4 key购买 nike

我想知道是否有人可以帮忙

我用的加密方式是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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com