1
votes

I'm doing an integration with another system and the data given is encrypted in AES-256-CBC(Java) and need to decrypt it in NodeJs in order to proceed.

I have tried many ways from internet and stuck in error. Below is the sample code of Java(decryption) which is working and NodeJs(my code of decryption)

private static final int ITERATION_COUNT = 65536;
private static final int KEY_LENGTH = 256;
private static final byte[] DEFAULT_IV = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

public static byte[] decryptToBytes(String src, String secret, String salt, byte[] iv) {
        try{
            IvParameterSpec ivspec = new IvParameterSpec(iv);

            SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
            KeySpec spec = new PBEKeySpec(secret.toCharArray(), salt.getBytes(), ITERATION_COUNT, KEY_LENGTH);
            SecretKey tmp = factory.generateSecret(spec);
            SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivspec);
            return cipher.doFinal(Base64.getDecoder().decode(src));
        }catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

public static String decrypt(String src, String secret, String salt, byte[] iv) {
        try{
            return new String(decryptToBytes(src, secret, salt, iv));
        }catch (Exception ex) {
            return null;
        }
    }

public static void main(String[] args) {
        String secret  = "abcd123456";
        String salt = "123abc";
        String plainText ="This is AES256 encryption test";
        String cipherText = "gbYgtu5EWxOYRSUmMsEtdn8oQLxBjejfwUBSRhhls08=";

        byte[] IV = new byte[16];

        String originalText = decrypt(cipherText,secret, salt, IV);

    }
import crypto from "crypto";
public aesCdcDecrypt(input: string) {
        let iterationCount = 65536;
        let keyLength = 256;
        let iv = new Buffer(16);
        let keyHex = "abcd123456";
        let salt = "123abc";

        let decryptText: string;
        try {
            crypto.pbkdf2(new Buffer(keyHex), new Buffer(salt), iterationCount, keyLength, "sha256", function (err, key) {
                let secretKey = key.toString("hex");
                let decipher = crypto.createDecipheriv("aes-256-cbc", secretKey, iv);
                decryptText = decipher.update(input, "binary", "utf8");
                decryptText += decipher.final("utf8");

                console.log('Result: ' + decryptText);
            });
        } catch (e) {
            console.log(e);
        }
        return decryptText;
    }

Result getting this error --> Error: Invalid key length at new Decipheriv (crypto.js:267:16) at Object.createDecipheriv (crypto.js:627:10)

1

1 Answers

2
votes

There are a few minor issues in your TS code:

  • key length is in bytes, not bits
  • new Buffer() does not decode base64 by default

Here's a working version (JS):

const crypto = require('crypto')
function aesCdcDecrypt(ciphertext) {
    let iterationCount = 65536;
    let keyLength = 32;
    let iv = Buffer.alloc(16);
    let keyHex = "abcd123456";
    let salt = "123abc";

    let key = crypto.pbkdf2Sync(keyHex, Buffer.from(salt), iterationCount, keyLength, "sha256");
    var cipher = crypto.createDecipheriv("aes-256-cbc", key, iv);
    cipher.setAutoPadding(true);
    let ciph = cipher.update(Buffer.from(ciphertext, "base64"));
    let ciphf = cipher.final();
    return Buffer.concat([ciph, ciphf]).toString();
}
console.log(aesCdcDecrypt("gbYgtu5EWxOYRSUmMsEtdn8oQLxBjejfwUBSRhhls08="));

Prints:

This is AES256 encryption test