使用PHP的AES 256 CTR解密的Node.js v10.16.0实现

时间:2020-03-18 10:57:18

标签: php node.js aes

我必须用于解密的密钥是一个80个字符长的字符串。 我无法弄清楚Node.js实现中此类键所需的iv的长度。

我正在尝试转换为Node.js的

PHP代码段:

protected function Decryption($theData, $theKey) {
 $method = 'aes-256-ctr';
 $nonceSize = openssl_cipher_iv_length($method);
 $nonce = mb_substr($theData, 0, $nonceSize, '8bit');
 $ciphertext = mb_substr($theData, $nonceSize, null, '8bit');
 $plaintext = openssl_decrypt( $ciphertext, $method, $theKey, OPENSSL_RAW_DATA, $nonce);
 return json_decode($plaintext);
}

Node.js实现,抛出无效的IV长度错误:

const crypto = require('crypto');
const nonce = crypto.randomBytes(16).toString('base64');
const decipher  = crypto.createDecipheriv('aes-256-ctr', theKey, nonce);
let plainText = decipher.update(theData, 'base64', 'utf8');
plainText += decipher.final('utf8');
console.log(plainText);

这可以通过使用不同长度的键来解决,但是在这种情况下,我需要使用80个字符。

编辑 更新为使用Getting error of Invalid IV Length while using aes-256-cbc for encryption in node中的修复程序后,此代码出现无效密钥长度错误:

const crypto = require('crypto');
var iv = new Buffer(crypto.randomBytes(16))
var nonce = iv.toString('hex').slice(0, 16);
const decipher  = crypto.createDecipheriv('aes-256-ctr', theKey, nonce);
let plainText = decipher.update(theData, 'base64', 'utf8');
plainText += decipher.final('utf8');
console.log(plainText);

0 个答案:

没有答案