Thursday, 8 June 2017

how to write exact encryption code in java and node?

Hi I need to translate the following code in Java:

    public static String encode(String chave, final String value)
        throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {

    final Key keySpec = new SecretKeySpec(chave.getBytes(), "AES");

    final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

    System.out.println(Hex.encodeHex(new byte[16]));


    cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(new byte[16]));

    final byte[] message = cipher.doFinal(value.getBytes());

    return new String(Hex.encodeHex(message));
}

to Node. I am trying:

var encrypt = function (key, data) {
var iv = new Buffer('');

decodeKey = new Buffer(key, "utf-8");
var cipher = crypto.createCipher('aes-128-cbc', decodeKey, iv);

cipher.setAutoPadding(true);
//return cipher.update(data, 'utf8', 'hex') + '   ' + cipher.final('hex');

var encrypted = Buffer.concat([
    cipher.update(data, "binary"),
    cipher.final()
]);

return encrypted.toString('hex');

};

But the result is not the same. It looks like there is an issue in the iv buffer but I can´t figure it out.

Any help?



via André Monteiro

No comments:

Post a Comment