I need to replicate Java encryption code using AES/EAX/NoPadding with BouncyCastle provider in node.js. The encrypted value will still need to be decrypted by the legacy Java decryption, so the salt and iv bytes need to stay the same length. In the node.js code I am able to generate the salt and secret key correctly. But I have an issue. What is equivalent algorithm to AES/EAX/NoPadding with BouncyCastle?
Existing Java:
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.security.SecureRandom;
import java.text.Normalizer;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.SecretKey;
import javax.crypto.Cipher;
public byte[] encrypt(byte[] plaintext, char[] password) {
byte[] saltBytes = "SaltString1234!".getBytes("UTF-8");
final byte[] salt = new byte[16];
System.arraycopy(saltBytes, 0, salt, 0, 16);
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(System.currentTimeMillis());
byte[] iv = new byte[8]; //
random.nextBytes(iv);
String normalizedPassword = Normalizer.normalize(new String(password), Normalizer.Form.NFC);
char[] currentPassword = normalizedPassword.toCharArray();
PBEKeySpec keySpec = new PBEKeySpec(currentPassword, salt, 1000, 128);
SecretKey derivedKey = newSecretKey("PBKDF2WithHmacSHA1", keySpec);
SecretKey secretKey = new SecretKeySpec(derivedKey.getEncoded(), "AES");
Provider provider = new BouncyCastleProvider();
Cipher cipher = newCipher("AES/EAX/NoPadding", provider);
final IvParameterSpec ivParamSpec = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParamSpec);
return cipher.doFinal(plaintext);
}
New node.js code:
const crypto = require('crypto');
function encrypt(plaintext, password) {
const salt = Buffer.from('SaltString1234!', 'utf8').subarray(0,16);
const secretKey = crypto.pbkdf2Sync(password.normalize('NFC'), salt, 1000, 16, 'sha1');
const iv = crypto.randomBytes(8);
const cipher = crypto.createCipheriv(
'aes-128-gcm'/* What algorithm be equivilent to AES/EAX/NoPadding with BouncyCastle? */,
secretKey,
iv
);
const ciphertextWithTag = Buffer.concat([
iv,
cipher.update(plaintext, 'utf8'),
cipher.final(),
cipher.getAuthTag()
]);
return ciphertextWithTag;
}