尝试使用PHP的AES-256-GCM解密 [英] Trying to decrypt with aes-256-gcm with php
问题描述
我想知道是否有人可以提供帮助,
I wondered whether anyone can help,
我正在使用aes-256-gcm加密方法,我可以加密,但不能解密.
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);
加密代码
$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 标签
(HMAC),并将其传递给解密功能.它不会自动为您保存(您还应该生成一个良好的IV并将其与密文一起存储).
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 指定为:
字符串openssl_encrypt(字符串$ data,字符串$ method,字符串$ key [,int $ options = 0 [,字符串$ iv =""[,字符串& $ tag = NULL [,字符串$aad =""[,int $ tag_length = 16]]]]]))
如果仔细观察,您将传入 $ tag_length
,其中应包含 $ tag
.
If you look closely, you're passing in $tag_length
where $tag
is expected.
这是它的外观:
加密:
$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的AES-256-GCM解密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!