node.js - 使用 nodejs 加密模块使用带有 iv 的 aes-256-cbc 解密密码
问题描述
我正在将 python AES-256 Encrypt/Decrypt 方法移植到其等效的 nodejs。但是在解密密码时在 nodejs 端出现错误。
crypto.js:267
this._handle.initiv(cipher, toBuf(key), toBuf(iv));
^
Error: Invalid IV length
at new Decipheriv (crypto.js:267:16)
at Object.createDecipheriv (crypto.js:627:10)
at CryptoUtils.AESDecrypt
python加密/解密方法:
def AESEncrypt(key, plaintext):
plaintext = AESPad(plaintext)
iv = os.urandom(AES.block_size)
cipher = AES.new(key, AES.MODE_CBC, iv)
return iv + cipher.encrypt(plaintext)
def AESDecrypt(key, ciphertext):
iv = ciphertext[:AES.block_size];
cipher = AES.new(key, AES.MODE_CBC, iv);
plaintext = cipher.decrypt(ciphertext[AES.block_size:]);
return AESUnpad(plaintext);
我的 nodejs 尝试转换它:
AESEncrypt(key, plaintext) {
const _plaintext = this.AESPad(plaintext)
const iv = crypto.randomBytes(AES_BLOCK_SIZE) //synchronous
const cipher = crypto
.createCipheriv("aes-256-cbc", key, iv)
.update(_plaintext)
return iv + cipher
}
AESDecrypt(key, ciphertext) {
const iv = ciphertext.slice(0, 16)
console.log("iv", iv)
const plaintext = crypto
.createDecipheriv("aes-256-cbc", key, iv)
.update(ciphertext.substring(16))
return this.AESUnpad(plaintext)
我究竟做错了什么?我的 nodejs 版本是v8.11.2
和 Python2.7.15rc1
解决方案
推荐阅读
- arrays - Bash:在命令行工作,但在脚本中使用时得到'curl:(1) 协议“https”不支持或在 libcurl 中禁用'
- matlab - 合并2个矩阵
- flink-statefun - Flink StatefulFunction 对检查点做出反应?
- dart - 如何在 Flutter 中拆分列表
- laravel - 如何从数据库中调用所有数据变量数组?拉拉维尔
- python - Pandas - 组合具有相似值的行(名称拼写变化)
- woocommerce - Woocommerce - 订单跟踪链接
- html - 引导代码在 Fiddle 中有效,但在 localhost 中无效?
- php - PHP 使用 header('Content-Type: audio/mpeg') 时使用 file_put_contents 复制日志条目;
- typescript - 如何使此更新 API 更高效、更短且不重复