aes-256-gcm 使用 PHP 加密,使用 javascript 解密

aes-256-gcm encrypt with PHP, decrypt with javascript

我在 javascript 端解密我的数据时遇到一些问题。 我成功地使用了 aes-256-cbc,但是使用了 aes-256-gcm,我遇到了一些麻烦。

所以我在 PHP 中有一个 API,在 Reactjs 中有一个前端。

见下方 PHP 方:

$algo = "aes-256-gcm";
$sKey = openssl_random_pseudo_bytes(16);
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher));

$sEncrypted = openssl_encrypt(
     json_encode($aData, true), 
     $algo, 
     $sKey, 
     $options=0, 
     $iv, 
     $tag
);


$aEncrypt = [
    "ciphertext" => base64_encode($sEncrypted),
    "iv"         => base64_encode($iv),      
    "tag"        => base64_encode($tag)
];

return $aEncrypt;

我javascript这边:

import crypto from 'crypto';

// Retrieve json
let obj_json = JSON.parse(data);

// Define variable from API call
let algo = 'aes-256-gcm';
let key = "xx"; // Retrieved previously
let encrypted_data = obj_json.ciphertext; // Seems no need to decode b64 since update function will do it
let tag = atob(obj_json.tag); // b64 decode
let iv = atob(obj_json.iv); // b64 decode

// Let's decrypt
let decipher = crypto.createDecipheriv(algo, key, iv);
decipher.setAuthTag(tag);
let decrypted = decipher.update(encrypted_data, 'base64','utf8');
decrypted += decipher.final('utf8');

我得到:

Error: Unsupported state or unable to authenticate data

我尝试了不同的库 (reactjs),但我总是遇到这个错误。 是不是编码iv或者tag有问题?

谢谢 :D

答案可以在这里找到:Encrypt string in PHP and decrypt in Node.js

您可能需要对自己的设置进行一些调整,但它应该可以工作!

干杯。

终于找到问题了

只是替换

let tag = atob(obj_json.tag); // b64 decode
let iv = atob(obj_json.iv); // b64 decode

来自

let tag = Buffer.from(obj_json.tag, 'base64');
let iv = Buffer.from(obj_json.iv, 'base64');