1 package org.bouncycastle.jcajce.provider.symmetric.util; 2 3 import java.security.InvalidAlgorithmParameterException; 4 import java.security.InvalidParameterException; 5 import java.security.SecureRandom; 6 import java.security.spec.AlgorithmParameterSpec; 7 8 import javax.crypto.KeyGeneratorSpi; 9 import javax.crypto.SecretKey; 10 import javax.crypto.spec.SecretKeySpec; 11 12 import org.bouncycastle.crypto.CipherKeyGenerator; 13 import org.bouncycastle.crypto.KeyGenerationParameters; 14 15 public class BaseKeyGenerator 16 extends KeyGeneratorSpi 17 { 18 protected String algName; 19 protected int keySize; 20 protected int defaultKeySize; 21 protected CipherKeyGenerator engine; 22 23 protected boolean uninitialised = true; 24 BaseKeyGenerator( String algName, int defaultKeySize, CipherKeyGenerator engine)25 protected BaseKeyGenerator( 26 String algName, 27 int defaultKeySize, 28 CipherKeyGenerator engine) 29 { 30 this.algName = algName; 31 this.keySize = this.defaultKeySize = defaultKeySize; 32 this.engine = engine; 33 } 34 engineInit( AlgorithmParameterSpec params, SecureRandom random)35 protected void engineInit( 36 AlgorithmParameterSpec params, 37 SecureRandom random) 38 throws InvalidAlgorithmParameterException 39 { 40 throw new InvalidAlgorithmParameterException("Not Implemented"); 41 } 42 engineInit( SecureRandom random)43 protected void engineInit( 44 SecureRandom random) 45 { 46 if (random != null) 47 { 48 engine.init(new KeyGenerationParameters(random, defaultKeySize)); 49 uninitialised = false; 50 } 51 } 52 engineInit( int keySize, SecureRandom random)53 protected void engineInit( 54 int keySize, 55 SecureRandom random) 56 { 57 try 58 { 59 if (random == null) 60 { 61 random = new SecureRandom(); 62 } 63 engine.init(new KeyGenerationParameters(random, keySize)); 64 uninitialised = false; 65 } 66 catch (IllegalArgumentException e) 67 { 68 throw new InvalidParameterException(e.getMessage()); 69 } 70 } 71 engineGenerateKey()72 protected SecretKey engineGenerateKey() 73 { 74 if (uninitialised) 75 { 76 engine.init(new KeyGenerationParameters(new SecureRandom(), defaultKeySize)); 77 uninitialised = false; 78 } 79 80 return new SecretKeySpec(engine.generateKey(), algName); 81 } 82 } 83