Memory leak at bouncycastle.jce.provider

2.1k views Asked by At

I'm running a java (openjdk:11.0.8) application using bouncycastle.jce.provider:

group: 'org.bouncycastle', name: 'bcprov-jdk15on', version: '1.65'

I noticed a memory leak and the dump shows that almost all of the memory is comsumed by

javax.crypto.JceSecurity -- > java.util.IdentityHashMap

This is how it looks like:

enter image description here

It seems that the hashMap gets bigger and bigger. I see 2 IdentityHashMaps in JceSecurity which states:

// Map<Provider,?> of the providers we already have verified
// value == PROVIDER_VERIFIED is successfully verified
// value is failure cause Exception in error case
private static final Map<Provider, Object> verificationResults =
        new IdentityHashMap<>();

// Map<Provider,?> of the providers currently being verified
private static final Map<Provider, Object> verifyingProviders =
        new IdentityHashMap<>();

How can this be overcome? how can a fix look like?

I'm adding below the way this provider is used, in case it is somehow relevant:

static {
    Security.addProvider(new BouncyCastleProvider());
}

public static String encrypt(String pkcs8Base64PublicKey,String text) throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    String publicKeyStr = canonizeKey(pkcs8Base64PublicKey);
    PublicKey publicKey = toPublicKey(publicKeyStr);
    Cipher cipher = Cipher.getInstance(DEFAULT_TRANSFORMATION);
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    byte[] encryptedText = cipher.doFinal(text.getBytes(Charset.forName("UTF-8")));
    return new String(Base64.getEncoder().encode(encryptedText), Charset.forName("UTF-8"));
}

public static String decrypt(String pkcs8Base64PrivateKey, String encryptedMessage) throws GeneralSecurityException {
    String privateKeyStr = canonizeKey(pkcs8Base64PrivateKey);
    PrivateKey privateKey = toPrivateKey(privateKeyStr);
    Cipher cipher = Cipher.getInstance(DEFAULT_TRANSFORMATION);
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    byte[] decryptedMessage = Base64.getDecoder().decode(encryptedMessage);
    return new String(cipher.doFinal(decryptedMessage), Charset.forName("UTF-8"));
}
1

There are 1 answers

0
Gergo On

I had the same problem, and I could solve it width this small code. I hope this can help somebody :) .

private static BouncyCastleProvider bouncycastleprovider = null;

public static synchronized BouncyCastleProvider getinstance () {

    if (bouncycastleprovider == null) {

        bouncycastleprovider = new BouncyCastleProvider();

    }
    return bouncycastleprovider;
}