简体   繁体   中英

encryptAES from Java to node.js

I have a Java algorithm for AES encryption and decryption and have to realize the decryption in JavaScript.

 public static final String ENCRYPTION_ALGORITHM = "AES/CBC/PKCS5Padding";
 public static String wrap(String clearText, String key) {
    byte[] iv = getIv();

    byte[] cipherText = encrypt(clearText, key, iv);
    byte[] wrapped = new byte[iv.length + cipherText.length];
    System.arraycopy(iv, 0, wrapped, 0, iv.length);
    System.arraycopy(cipherText, 0, wrapped, 16, cipherText.length);

    return new String(Base64.encodeBase64(wrapped));
}

private static byte[] encrypt(String clearText, String key, byte[] iv) {
    try {
        Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
        AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
        params.init(new IvParameterSpec(iv));
        cipher.init(Cipher.ENCRYPT_MODE, getKey(key), params);
        return cipher.doFinal(clearText.getBytes());
    } catch (GeneralSecurityException e) {
        throw new RuntimeException("Failed to encrypt.", e);
    }
}

private static SecretKeySpec getKey(String key) {
    try {
        return new SecretKeySpec(Hex.decodeHex(key.toCharArray()), "AES");
    } catch (DecoderException e) {
        throw new RuntimeException("Failed to generate a secret key spec", e);
    }
}

private static byte[] getIv() {
    byte[] iv = new byte[16];
    new SecureRandom().nextBytes(iv);

    return iv;
}

I have wrote javascript code but it generate incorrect result:

var responseBody = JSON.stringify({"key":"215467ryhfdjeu8373t4"});
var initializationVector = crypto.randomBytes(16);
key = new Buffer(key.substring(0,32), 'hex');
var cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
var encrypted = cipher.update(new Buffer(responseBody)) +     cipher.final('hex');
var encoded = new Buffer(initializationVector+encrypted, 'binary');
return encoded;

Could you please help me to rewrite Java wrap function to javascript(NodeJS)?

Problem is fixed.

The problem was in concatenate of the buffers. The operator "+" not correct for this. Need use the default method.

Buffer.concat([initializationVector, encrypted])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM