Search code examples
javascriptnode.jsencryptionnode-crypto

I am trying to convert Java AES encryption decryption to NodeJs. This is what I have tried so far


Encryption:

private static String secretKey = "boooooooooom!!!!";
private static String salt = "ssshhhhhhhhhhh!!!!";

public static String encrypt(String strToEncrypt, String secret) 
{
    try 
    {
        byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
        IvParameterSpec ivspec = new IvParameterSpec(iv);

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

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivspec);
        return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
    } 
    catch (Exception e) 
    {
        System.out.println("Error while encrypting: " + e.toString());
    }
    return null;
}

Decryption:

private static String secretKey = "boooooooooom!!!!";
private static String salt = "ssshhhhhhhhhhh!!!!";

public static String decrypt(String strToDecrypt, String secret) {
    try 
    {
        byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
        IvParameterSpec ivspec = new IvParameterSpec(iv);

        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
        KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), salt.getBytes(), 65536, 256);
        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 new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
    } 
    catch (Exception e) {
        System.out.println("Error while decrypting: " + e.toString());
    }
    return null;
}

I have searched a lot about this. I got these questions on stack overflow

Difference in key lengths between crypto.pbkdf2 (node.js) and PBEKeySpec, AES/CBC/PKCS5PADDING IV - Decryption in NodeJs (Encrypted in Java) I have tried both of them but none of them resolved my query.

What I have tried so far is,

function encrypt(plainText, secretKey,randomeString) {

    const key = crypto.pbkdf2Sync(secretKey, salt, 65536, 16, digest);
    const iv = Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]);
    const cipher = crypto.createCipheriv(algorithm, key, iv);
    let encrypted = cipher.update(plainText, 'utf8', 'base64')
    encrypted += cipher.final('base64');      
    return encrypted;
};

function decrypt(strToDecrypt, secretKey, randomeString) {

    const key = crypto.pbkdf2Sync(secretKey, salt, 65536, 16, digest);

    const iv = Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]);

    const decipher = crypto.createDecipheriv(algorithm, key, iv);
    let decrypted = decipher.update(strToDecrypt, 'base64');
    decrypted += decipher.final();
    return decrypted;
}

Solution

  • This Node.js code should produce the same results as your Java code. I also made the secretKey variable a parameter of the encrypt / decrypt functions.

    const crypto = require('crypto');
    
    const algorithm = 'aes-256-cbc';
    const salt = "ssshhhhhhhhhhh!!!!";
    const digest = 'sha256';
    
    function encrypt(plainText, secretKey) {
    
        const key = crypto.pbkdf2Sync(secretKey, salt, 65536, 32, digest);
        const iv = Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]);
    
        const cipher = crypto.createCipheriv(algorithm, key, iv);
        let encrypted = cipher.update(plainText, 'utf8', 'base64')
        encrypted += cipher.final('base64');
        return encrypted;
    };
    
    function decrypt(strToDecrypt, secretKey) {
    
        const key = crypto.pbkdf2Sync(secretKey, salt, 65536, 32, digest);
        const iv = Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]);
    
        const decipher = crypto.createDecipheriv(algorithm, key, iv);
        let decrypted = decipher.update(strToDecrypt, 'base64');
        decrypted += decipher.final();
        return decrypted;
    }
    
    const key = "boooooooooom!!!!";
    const cipherText = encrypt("test", key);
    console.log("Ciphertext:", cipherText);
    const plainText = decrypt(cipherText, key);
    console.log("Plaintext:", plainText);