Skip to content

Commit

Permalink
[improve][misc] Improve AES-GCM cipher performance (apache#23122)
Browse files Browse the repository at this point in the history
  • Loading branch information
ocadaruma authored and Technoboy- committed Aug 6, 2024
1 parent fff41c3 commit 354a9f0
Showing 1 changed file with 13 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,9 @@ public class MessageCryptoBc implements MessageCrypto<MessageMetadata, MessageMe

// Ideally the transformation should also be part of the message property. This will prevent client
// from assuming hardcoded value. However, it will increase the size of the message even further.
private static final String RSA_TRANS = "RSA/NONE/OAEPWithSHA1AndMGF1Padding";
private static final String AESGCM = "AES/GCM/NoPadding";

public static final String RSA_TRANS = "RSA/NONE/OAEPWithSHA1AndMGF1Padding";
public static final String AESGCM = "AES/GCM/NoPadding";
private static final String AESGCM_PROVIDER_NAME;
private static KeyGenerator keyGenerator;
private static final int tagLen = 16 * 8;
private byte[] iv = new byte[IV_LEN];
Expand Down Expand Up @@ -121,6 +121,15 @@ public class MessageCryptoBc implements MessageCrypto<MessageMetadata, MessageMe
// Initial seed
secureRandom.nextBytes(new byte[IV_LEN]);

// Prefer SunJCE provider for AES-GCM for performance reason.
// For cases where SunJCE is not available (e.g. non-hotspot JVM), use BouncyCastle as fallback.
String sunJceProviderName = "SunJCE";
if (Security.getProvider(sunJceProviderName) != null) {
AESGCM_PROVIDER_NAME = sunJceProviderName;
} else {
AESGCM_PROVIDER_NAME = BouncyCastleProvider.PROVIDER_NAME;
}

// Add provider only if it's not in the JVM
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
Security.addProvider(new BouncyCastleProvider());
Expand All @@ -143,7 +152,7 @@ public SecretKey load(ByteBuffer key) {

try {

cipher = Cipher.getInstance(AESGCM, BouncyCastleProvider.PROVIDER_NAME);
cipher = Cipher.getInstance(AESGCM, AESGCM_PROVIDER_NAME);
// If keygen is not needed(e.g: consumer), data key will be decrypted from the message
if (!keyGenNeeded) {

Expand Down

0 comments on commit 354a9f0

Please sign in to comment.