My node js is using below decryption/encryption,
const crypto = require('crypto');
// set random encryption key
const ENC_KEY = Buffer.from("bf3c199c2470cb477d907b1e0917c17bbf3c199c2470cb477d907b1e0917c17b", "hex");
// set random initialisation vector
const IV = Buffer.from("5183666c72eec9e45183666c72eec9e4", "hex");
var encrypt = ((val) => {
let cipher = crypto.createCipheriv('aes-256-cbc', ENC_KEY, IV);
let encrypted = cipher.update(val, 'utf8', 'base64');
encrypted += cipher.final('base64');
return encrypted;
});
var decrypt = ((encrypted) => {
let decipher = crypto.createDecipheriv('aes-256-cbc', ENC_KEY, IV);
let decrypted = decipher.update(encrypted, 'base64', 'utf8');
return (decrypted + decipher.final('utf8'));
});
encrypted_key = encrypt(miny);
console.log(encrypted_key);
original_phrase = decrypt(encrypted_key);
I am trying to decrypt/encrypt the same in Java using the code below.
String seed = "1233434343434343" //some key
String encrypted = the encrypted string from node js
Ex: 8ci5qsYa5W/Z4tLNVjn1FbL0vwDBzLE2rv0X0Y0p (json encrypted)
private static String decrypt(String encrypted, String seed)
throws Exception {
byte[] keyb = seed.getBytes("utf-8");
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] thedigest = md.digest(keyb);
SecretKeySpec skey = new SecretKeySpec(thedigest, "AES");
Cipher dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
dcipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(seed.getBytes("UTF-8"), "AES"), new IvParameterSpec(iv));
byte[] clearbyte = dcipher.doFinal(DatatypeConverter
.parseHexBinary(encrypted));
return new String(clearbyte);
}
But it is always throwing error saying that Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
I tried some other options provided in stack overflow but no luck. What can I do to decrypt the message from NodeJS in Java?