0

We have a sender application (node.js) which sends to a Java application some symmetric encrypted XML strings with an AES 128 key.

When the Java application tries to decrypt the content with the provided key the following error will be thrown:

javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption. at com.sun.crypto.provider.CipherCore.unpad(CipherCore.java:975) at com.sun.crypto.provider.CipherCore.fillOutputBuffer(CipherCore.java:1056) at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:853) at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446) at javax.crypto.Cipher.doFinal(Cipher.java:2168)

public generateKey(): Buffer {
    return crypto.generateKeySync('aes', { length: 128 }).export();
}

// Encrypt content with key
public encryptSymmetric(content: string, encryptionKey: Buffer): Buffer {
    const iv = Buffer.from(crypto.randomBytes(this.IV_LENGTH)).toString('hex').slice(0, this.IV_LENGTH);
    const cipher = crypto.createCipheriv('aes-128-cbc', encryptionKey, iv);
    let encrypted = cipher.update(content);

    encrypted = Buffer.concat([encrypted, cipher.final()]);
    return encrypted;
    //return iv + ':' + encrypted.toString('hex');
}

Java receiver: decrypt with key

private static byte[] decryptContent(SecretKeySpec key, byte[] content) throws GeneralSecurityException {
    Cipher cipher = Cipher.getInstance('AES');
    cipher.init(Cipher.DECRYPT_MODE, key);
    return cipher.doFinal(content); // EXCEPTION
}

I have no idea to solve this specific problem, at encryption level there many different options like AES CBC or GCM. I hope you can help me. We can change only the sender code!

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
3t34z3
  • 1
  • 2
  • In the Java code, the IV is missing (for this, the IV must be returned in the NodeJS code in addition to the ciphertext, see e.g. the commented out line)! Also, mode and padding should be specified when instantiating the `Cipher` object: `getInstance("AES/CBC/PKCS5Padding")`. – Topaco Mar 10 '22 at 11:03
  • @Topaco, we are not allowed to change the JAVA implementation, cause its already in use, but the JavaScript Client, so we have to adjust our code to the JAVA code. The question here, how is the IV handled in default by JAVA, are there some defaults about padding? – 3t34z3 Mar 10 '22 at 12:13
  • 1
    The Java code developer probably has little knowledge about encryption. Since the Java code does not specify mode or padding, provider-dependent default values are used. For the SunJCE provider these are ECB and PKCS#7 padding. ECB does not require an IV, but is insecure. ECB must be specified in the NodeJS code. PKCS#7 padding is the default. – Topaco Mar 10 '22 at 12:55

0 Answers0