0

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?

Locke
  • 7,626
  • 2
  • 21
  • 41
  • 1
    I don't know too much about encryption, but have you tried removing `/PKCS5Padding` from `Cipher.getInstance` in the java version? My guess is that it is expecting that type of padding to decrypt, but it isn't being used while encrypting. – Locke Oct 02 '20 at 14:09
  • You're not using PKCS5 padding in the encryption. – m0skit0 Oct 02 '20 at 14:23
  • i found this link and it is working: https://stackoverflow.com/questions/50922462/aes-cbc-pkcs5padding-iv-decryption-in-nodejs-encrypted-in-java/50925146 – user6933210 Oct 02 '20 at 14:44

0 Answers0