Skip to content

Commit

Permalink
KeyGenUtils: re-use the bouncy castle instance to avoid the memory leak.
Browse files Browse the repository at this point in the history
  • Loading branch information
ArneBab committed Oct 10, 2018
1 parent a89604d commit f86e4f8
Showing 1 changed file with 5 additions and 7 deletions.
12 changes: 5 additions & 7 deletions src/freenet/crypt/KeyGenUtils.java
Expand Up @@ -36,9 +36,7 @@
*/
public final class KeyGenUtils {

static {
java.security.Security.insertProviderAt(new BouncyCastleProvider(), 1);
}
private static BouncyCastleProvider bcProvider = new BouncyCastleProvider();

/**
* Generates a public/private key pair formatted for the algorithm specified
Expand All @@ -51,7 +49,7 @@ public static KeyPair genKeyPair(KeyPairType type) {
throw new UnsupportedTypeException(type);
}
try {
KeyPairGenerator kg = KeyPairGenerator.getInstance(type.alg);
KeyPairGenerator kg = KeyPairGenerator.getInstance(type.alg, bcProvider);
kg.initialize(type.spec);
return kg.generateKeyPair();
} catch (NoSuchAlgorithmException e) {
Expand All @@ -72,7 +70,7 @@ public static PublicKey getPublicKey(KeyPairType type, byte[] pub){
throw new UnsupportedTypeException(type);
}
try {
KeyFactory kf = KeyFactory.getInstance(type.alg);
KeyFactory kf = KeyFactory.getInstance(type.alg, bcProvider);
X509EncodedKeySpec xks = new X509EncodedKeySpec(pub);
return kf.generatePublic(xks);
} catch (NoSuchAlgorithmException e) {
Expand Down Expand Up @@ -127,7 +125,7 @@ public static KeyPair getKeyPair(KeyPairType type, byte[] pub, byte[] pri) {
throw new UnsupportedTypeException(type);
}
try {
KeyFactory kf = KeyFactory.getInstance(type.alg);
KeyFactory kf = KeyFactory.getInstance(type.alg, bcProvider);

PublicKey pubK = getPublicKey(type, pub);

Expand Down Expand Up @@ -174,7 +172,7 @@ public static KeyPair getKeyPair(PublicKey pubK, PrivateKey privK){
*/
public static SecretKey genSecretKey(KeyType type){
try{
KeyGenerator kg = KeyGenerator.getInstance(type.alg);
KeyGenerator kg = KeyGenerator.getInstance(type.alg, bcProvider);
kg.init(type.keySize);
return kg.generateKey();
} catch (NoSuchAlgorithmException e) {
Expand Down

0 comments on commit f86e4f8

Please sign in to comment.