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 // BEGIN android-added 60 if (random == null) { 61 random = new SecureRandom(); 62 } 63 // END android-added 64 engine.init(new KeyGenerationParameters(random, keySize)); 65 uninitialised = false; 66 } 67 catch (IllegalArgumentException e) 68 { 69 throw new InvalidParameterException(e.getMessage()); 70 } 71 } 72 engineGenerateKey()73 protected SecretKey engineGenerateKey() 74 { 75 if (uninitialised) 76 { 77 engine.init(new KeyGenerationParameters(new SecureRandom(), defaultKeySize)); 78 uninitialised = false; 79 } 80 81 return new SecretKeySpec(engine.generateKey(), algName); 82 } 83 } 84