AES / CBC / PKCS5PADDING IV - 从Java到NodeJ的解密

时间:2018-06-04 07:06:25

标签: javascript java node.js encryption node-crypto

我正在尝试在NodeJ中解密。它在Java中工作。但是我无法在Node中实现相同的功能。

我使用的是node-version:8.4

请查找我的NodeJs代码:

var crypto = require('crypto');
function decryption (message, key) {
    var messageArray = Buffer.from(message, 'base64');
    // var kekbuf =  Buffer(key, 'utf8');

    var ivBuffer = new Buffer([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);
    var iv = ivBuffer.slice(0, 16);

    var decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
    decipher.setAutoPadding(false);
    var dec = decipher.update(messageArray, 'base64');

    dec += decipher.final();
    return dec.toString();
}

请找到有用的Java代码

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

class Test1 {
  public String decrypt(String message, String key) throws Exception {
    DatatypeConverter dtc = null;
    byte[] messagArray = dtc.parseBase64Binary(message);
    byte[] keyArray = dtc.parseBase64Binary(key);

    byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
    IvParameterSpec ivspec = new IvParameterSpec(iv);

    SecretKey secretKey = new SecretKeySpec(keyArray, "AES");
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");

    cipher.init(Cipher.DECRYPT_MODE, secretKey, ivspec);
    return new String(cipher.doFinal(messagArray));
  }
}

我收到了不同的解密文字。我无法在NodeJ中获得与Java相同的结果。

请帮助我。

1 个答案:

答案 0 :(得分:0)

使用crypto2库,这个库修复了iv问题:

    const crypto2 = require('crypto2'); 

    AESDecrypt: function (encrypted, secretKey) {
            return new Promise((resolve, reject) => {
                if (encrypted && secretKey) {
                    crypto2.decrypt.aes256cbc(encrypted, secretKey, (err, decrypted) => {
                        if (err) {
                            reject(err);
                        } else {
                            resolve(decrypted);
                        }
                    });
                } else {
                    reject('Crypt - Invalid params!');
                }
            })
        }