AES Encryption in Nodjs and decryption in JAVA

Viewed 302

I am trying to make use of AES CTR encryption in nodejs and decryption of the same in JAVA. I have attached the code here. The decryption happens well in nodejs while in java it is not readable. I am not sure what mistake I have made. please help.

NODEJS ENCRYPTION

const crypto = require('crypto');
const algorithm = 'aes-256-ctr';
const secret = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);

class Encryptor {

    constructor() {
    }

    encrypt(text) {
        let cipher = crypto.createCipheriv(algorithm, secret, iv);
        let encrypted = cipher.update(text);
        encrypted = Buffer.concat([encrypted, cipher.final()]);
        return { iv: iv.toString('hex'), encryptedData: encrypted.toString('hex'), key: secret.toString('hex') };
    }           

    decrypt(text) {
        let encryptedText = Buffer.from(text.encryptedData, 'hex');
        let iv = Buffer.from(text.iv, 'hex');
        let decipher = crypto.createDecipheriv(algorithm, secret, iv);
        let decrypted = decipher.update(encryptedText);
        decrypted = Buffer.concat([decrypted, decipher.final()]);
        return decrypted.toString();
   }    
}

module.exports = new Encryptor();

JAVA DECRYPTION

    public static String decrypt(String encryptedText, String iv, String key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException, DecoderException, InvalidAlgorithmParameterException {
        cipher = Cipher.getInstance("AES/CTR/NoPadding");
        privateKey = new SecretKeySpec(Hex.decodeHex(key),  "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(Hex.decodeHex(iv));


        cipher.init(Cipher.DECRYPT_MODE, privateKey, ivSpec);
        byte[] afinal = cipher.doFinal(encryptedText.getBytes());
        return new String(afinal);
    }


0 Answers
Related