首页 > 解决方案 > 使用 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

标签: node.jsencryption

解决方案


推荐阅读