1package org.bouncycastle.jcajce.provider.asymmetric.dsa; 2 3import java.security.AlgorithmParameters; 4import java.security.InvalidAlgorithmParameterException; 5import java.security.InvalidParameterException; 6import java.security.SecureRandom; 7import java.security.spec.AlgorithmParameterSpec; 8import java.security.spec.DSAParameterSpec; 9 10import org.bouncycastle.crypto.digests.SHA256Digest; 11import org.bouncycastle.crypto.generators.DSAParametersGenerator; 12import org.bouncycastle.crypto.params.DSAParameterGenerationParameters; 13import org.bouncycastle.crypto.params.DSAParameters; 14import org.bouncycastle.jce.provider.BouncyCastleProvider; 15 16public class AlgorithmParameterGeneratorSpi 17 extends java.security.AlgorithmParameterGeneratorSpi 18{ 19 protected SecureRandom random; 20 protected int strength = 1024; 21 protected DSAParameterGenerationParameters params; 22 23 protected void engineInit( 24 int strength, 25 SecureRandom random) 26 { 27 if (strength < 512 || strength > 3072) 28 { 29 throw new InvalidParameterException("strength must be from 512 - 3072"); 30 } 31 32 if (strength <= 1024 && strength % 64 != 0) 33 { 34 throw new InvalidParameterException("strength must be a multiple of 64 below 1024 bits."); 35 } 36 37 if (strength > 1024 && strength % 1024 != 0) 38 { 39 throw new InvalidParameterException("strength must be a multiple of 1024 above 1024 bits."); 40 } 41 42 this.strength = strength; 43 this.random = random; 44 } 45 46 protected void engineInit( 47 AlgorithmParameterSpec genParamSpec, 48 SecureRandom random) 49 throws InvalidAlgorithmParameterException 50 { 51 throw new InvalidAlgorithmParameterException("No supported AlgorithmParameterSpec for DSA parameter generation."); 52 } 53 54 protected AlgorithmParameters engineGenerateParameters() 55 { 56 DSAParametersGenerator pGen; 57 58 if (strength <= 1024) 59 { 60 pGen = new DSAParametersGenerator(); 61 } 62 else 63 { 64 pGen = new DSAParametersGenerator(new SHA256Digest()); 65 } 66 67 if (random == null) 68 { 69 random = new SecureRandom(); 70 } 71 72 if (strength == 1024) 73 { 74 params = new DSAParameterGenerationParameters(1024, 160, 80, random); 75 pGen.init(params); 76 } 77 else if (strength > 1024) 78 { 79 params = new DSAParameterGenerationParameters(strength, 256, 80, random); 80 pGen.init(params); 81 } 82 else 83 { 84 pGen.init(strength, 20, random); 85 } 86 87 DSAParameters p = pGen.generateParameters(); 88 89 AlgorithmParameters params; 90 91 try 92 { 93 params = AlgorithmParameters.getInstance("DSA", BouncyCastleProvider.PROVIDER_NAME); 94 params.init(new DSAParameterSpec(p.getP(), p.getQ(), p.getG())); 95 } 96 catch (Exception e) 97 { 98 throw new RuntimeException(e.getMessage()); 99 } 100 101 return params; 102 } 103} 104