Khay
Khay

Reputation: 1570

Java to Node.js AES/ECB/PKCS5Padding Encryption

I have the following encrypt function in JAVA. I am trying to write the same encryption in Node.js using cipher from crypto. But, the output is not the same. It is using the same key and input.

JAVA

public static String encrypt(String input, String key) {
    byte[] crypted = null;
    try {
        SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, skey);
        crypted = cipher.doFinal(input.getBytes());
    } catch (Exception e) {
        System.out.println(e.toString());
    }
    String result = new String(Base64.encodeBase64(crypted));
    return result.replace("+", "-");
}

Sample output: 0HCkcjWj/PoCZ4ZUFJARs/m4kstigMFk8dQnT0uNhog= (44 characters)

Node.js

encrypt = (input, key) => { 
    const algorithm = 'aes-128-cbc';   
    key = crypto.scryptSync(key, 'salt', 16);       
    const iv = Buffer.alloc(16, 0);
    const cipher = crypto.createCipheriv(algorithm, key, iv);
    cipher.setAutoPadding(true);
    let encrypted = cipher.update(input, 'utf8', 'base64');
    encrypted += cipher.final('base64');
    return encrypted.replace('+','-');
}

Sample output: ZHtEbAhrIo7vWOjdMNgW6Q== (24 characters)

Thanks in advance.

Upvotes: 1

Views: 4096

Answers (1)

Topaco
Topaco

Reputation: 49341

So that the NodeJS code is functionally identical to the Java code, in the NodeJS code:

  • ECB mode must be used instead of CBC mode:

    const algorithm = 'aes-128-ecb';
    ...
    //const iv = Buffer.alloc(16, 0); // remove
    const cipher = crypto.createCipheriv(algorithm, key, null);
    

    Note, however, that ECB doesn't use an IV, is generally insecure and should therefore not be used, [1]. Better alternatives are CBC mode (confidentiality) or GCM mode (confidentiality, authenticity/integrity), [2], [3].

  • No key derivation function may be applied [4], i.e. the following line must be removed:

    key = crypto.scryptSync(key, 'salt', 16); 
    

Upvotes: 3

Related Questions