I'm working on a piece of code which encrypt data in Java, and I need to decrypt it in nodejs. I am having issues with the decryption.
I'm adding the salt + the encrypted bytes all together and encode them in base64 in the java side.
on the node side i'm decoding base64, then slicing the salt and encrypted bytes. but i'm getting an error while trying to decrypt the string. any ideas?
Java encrypt:
private Key createKey(final byte[] salt) {
final PBEKeySpec spec = new PBEKeySpec(KEY,
salt,
20000,
256);
final SecretKey secretKey;
secretKey = keyFactory.generateSecret(spec);
return new SecretKeySpec(secretKey.getEncoded(), 'AES');
}
public String encrypt(final String message) {
final byte[] salt = secureRandom.nextBytes(SALT_LENGTH);
final Key key = createKey(salt);
final Cipher encryptingCipher = createCipher(Cipher.ENCRYPT_MODE, key, salt);
final byte[] messageBytes = message.getBytes(StandardCharsets.UTF_8);
final byte[] encryptedBytes = doFinal(encryptingCipher, messageBytes);
final byte[] data = ArrayUtils.addAll(salt, encryptedBytes);
return BaseEncoding.base64().encode(data);
}
Nodejs decrypt:
const decrypted = new Buffer(data, 'base64').toString('ascii');
const salt = decrypted.slice(0, AESEncryptor.SALT_LENGTH);
const encryptedBytes = decrypted.slice(AESEncryptor.SALT_LENGTH);
crypto.pbkdf2(KEY, salt, 20000, 256, (err, key) => {
var decipher = crypto.createDecipheriv('aes-256-cbc', key, salt);
var decoded = decipher.update(encryptedBytes, 'binary', 'utf8') + decipher.final('utf8');
console.log('decoded', decoded);
});
That's the error i'm getting:
Error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt