@Override public AsymmetricCipherKeyPairGenerator createAsymmetricCipherKeyPairGenerator(final boolean initWithDefaults) { final ElGamalKeyPairGenerator generator = new ElGamalKeyPairGenerator(); if (initWithDefaults) { /* * How certain do we want to be that the chosen primes are really primes. * <p> * The higher this number, the more tests are done to make sure they are primes (and not composites). * <p> * See: <a href="http://crypto.stackexchange.com/questions/3114/what-is-the-correct-value-for-certainty-in-rsa-key-pair-generation">What is the correct value for “certainty” in RSA key pair generation?</a> * and * <a href="http://crypto.stackexchange.com/questions/3126/does-a-high-exponent-compensate-for-a-low-degree-of-certainty?lq=1">Does a high exponent compensate for a low degree of certainty?</a> */ final int certainty = 12; final SecureRandom random = new SecureRandom(); ElGamalParametersGenerator pGen = new ElGamalParametersGenerator(); pGen.init(4096, certainty, random); ElGamalParameters elGamalParameters = pGen.generateParameters(); generator.init(new ElGamalKeyGenerationParameters(random, elGamalParameters)); } return generator; }
@Override public AsymmetricCipherKeyPairGenerator createAsymmetricCipherKeyPairGenerator(final boolean initWithDefaults) { final DSAKeyPairGenerator generator = new DSAKeyPairGenerator(); if (initWithDefaults) { /* * How certain do we want to be that the chosen primes are really primes. * <p> * The higher this number, the more tests are done to make sure they are primes (and not composites). * <p> * See: <a href="http://crypto.stackexchange.com/questions/3114/what-is-the-correct-value-for-certainty-in-rsa-key-pair-generation">What is the correct value for “certainty” in RSA key pair generation?</a> * and * <a href="http://crypto.stackexchange.com/questions/3126/does-a-high-exponent-compensate-for-a-low-degree-of-certainty?lq=1">Does a high exponent compensate for a low degree of certainty?</a> */ final int certainty = 12; final SecureRandom random = new SecureRandom(); final DSAParametersGenerator pGen = new DSAParametersGenerator(); pGen.init(4096, certainty, random); final DSAParameters dsaParameters = pGen.generateParameters(); final DSAKeyGenerationParameters dsaKeyGenerationParameters = new DSAKeyGenerationParameters(random, dsaParameters); generator.init(dsaKeyGenerationParameters); } return generator; }
@Ignore @Test public void generateManySymmetricKeys() throws Exception { final String transformation = "RSA/ECB/OAEPWITHSHA1ANDMGF1PADDING"; final String engine = CryptoRegistry.splitTransformation(transformation)[0]; final AsymmetricCipherKeyPairGenerator keyPairGenerator = CryptoRegistry.getInstance().createKeyPairGenerator(engine, true); final long startAllKeys = System.currentTimeMillis(); final int keyCount = 10; for (int i = 0; i < keyCount; ++i) { final long startThisKey = System.currentTimeMillis(); keyPairGenerator.generateKeyPair(); logger.info("Generated key #{} in {}ms", i, System.currentTimeMillis() - startThisKey); } final long durationAllKeys = System.currentTimeMillis() - startAllKeys; logger.info("Generated {} keys in {}ms, taking in average {}ms per key.", keyCount, durationAllKeys, durationAllKeys / keyCount); }
private AsymmetricCipherKeyPairGenerator createAsymmetricCipherKeyPairGenerator(final CreatePgpKeyParam createPgpKeyParam, final int keyIndex) throws NoSuchAlgorithmException { final CryptoRegistry cryptoRegistry = CryptoRegistry.getInstance(); final AsymmetricCipherKeyPairGenerator keyPairGenerator; switch (createPgpKeyParam.getAlgorithm()) { case DSA_AND_EL_GAMAL: if (keyIndex == 0) { // master-key keyPairGenerator = cryptoRegistry.createKeyPairGenerator("DSA", false); keyPairGenerator.init(createDsaKeyGenerationParameters(createPgpKeyParam)); } else { // sub-key 1 keyPairGenerator = cryptoRegistry.createKeyPairGenerator("ElGamal", false); keyPairGenerator.init(createElGamalKeyGenerationParameters(createPgpKeyParam)); } break; case RSA: keyPairGenerator = cryptoRegistry.createKeyPairGenerator("RSA", false); keyPairGenerator.init(createRsaKeyGenerationParameters(createPgpKeyParam)); break; default: throw new IllegalStateException("Unknown algorithm: " + createPgpKeyParam.getAlgorithm()); } return keyPairGenerator; }
@Override public AsymmetricCipherKeyPairGenerator createAsymmetricCipherKeyPairGenerator(final boolean initWithDefaults) { final GOST3410KeyPairGenerator generator = new GOST3410KeyPairGenerator(); // TODO implement meaningful and secure defaults! if (initWithDefaults) throw new UnsupportedOperationException("NYI: initWithDefaults"); return generator; }
@Override public AsymmetricCipherKeyPairGenerator createAsymmetricCipherKeyPairGenerator(final boolean initWithDefaults) { final RSAKeyPairGenerator generator = new RSAKeyPairGenerator(); if (initWithDefaults) { if (random == null) random = new SecureRandom(); generator.init(new RSAKeyGenerationParameters(defaultPublicExponent, random, 4096, defaultCertainty)); } return generator; }
@Override public AsymmetricCipherKeyPairGenerator createAsymmetricCipherKeyPairGenerator(final boolean initWithDefaults) { final DHBasicKeyPairGenerator generator = new DHBasicKeyPairGenerator(); // TODO implement meaningful and secure defaults! if (initWithDefaults) throw new UnsupportedOperationException("NYI: initWithDefaults"); // if (initWithDefaults) // generator.init(new DHKeyGenerationParameters(new SecureRandom(), new DHParameters(p, g, q))); return generator; }
@Override public AsymmetricCipherKeyPairGenerator createAsymmetricCipherKeyPairGenerator(final boolean initWithDefaults) { final NaccacheSternKeyPairGenerator generator = new NaccacheSternKeyPairGenerator(); // TODO implement meaningful and secure defaults! if (initWithDefaults) throw new UnsupportedOperationException("NYI: initWithDefaults"); return generator; }
private void encodeDecode(final String transformation) throws Exception { final String engine = CryptoRegistry.splitTransformation(transformation)[0]; final AsymmetricCipherKeyPairGenerator keyPairGenerator = CryptoRegistry.getInstance().createKeyPairGenerator(engine, true); final AsymmetricCipherKeyPair keyPair = keyPairGenerator.generateKeyPair(); final byte[] encodedPrivateKey = CryptoRegistry.getInstance().encodePrivateKey(keyPair.getPrivate()); final byte[] encodedPublicKey = CryptoRegistry.getInstance().encodePublicKey(keyPair.getPublic()); final AsymmetricKeyParameter decodedPrivateKey = CryptoRegistry.getInstance().decodePrivateKey(encodedPrivateKey); final AsymmetricKeyParameter decodedPublicKey = CryptoRegistry.getInstance().decodePublicKey(encodedPublicKey); final byte[] plainText = new byte[100 + secureRandom.nextInt(40)]; secureRandom.nextBytes(plainText); final Cipher cipher = CryptoRegistry.getInstance().createCipher(transformation); cipher.init(CipherOperationMode.ENCRYPT, keyPair.getPublic()); final byte[] encrypted1 = cipher.doFinal(plainText); cipher.init(CipherOperationMode.ENCRYPT, decodedPublicKey); final byte[] encrypted2 = cipher.doFinal(plainText); cipher.init(CipherOperationMode.DECRYPT, keyPair.getPrivate()); final byte[] decrypted1a = cipher.doFinal(encrypted1); final byte[] decrypted2a = cipher.doFinal(encrypted2); cipher.init(CipherOperationMode.DECRYPT, decodedPrivateKey); final byte[] decrypted1b = cipher.doFinal(encrypted1); final byte[] decrypted2b = cipher.doFinal(encrypted2); Assert.assertArrayEquals(plainText, decrypted1a); Assert.assertArrayEquals(plainText, decrypted1b); Assert.assertArrayEquals(plainText, decrypted2a); Assert.assertArrayEquals(plainText, decrypted2b); }
public EphemeralKeyPairGenerator(AsymmetricCipherKeyPairGenerator gen, KeyEncoder keyEncoder) { this.gen = gen; this.keyEncoder = keyEncoder; }
/** * we generate a self signed certificate for the sake of testing - DSA */ public void checkCreation2() throws Exception { // // set up the keys // AsymmetricKeyParameter privKey; AsymmetricKeyParameter pubKey; AsymmetricCipherKeyPairGenerator kpg = new DSAKeyPairGenerator(); BigInteger r = new BigInteger("68076202252361894315274692543577577550894681403"); BigInteger s = new BigInteger("1089214853334067536215539335472893651470583479365"); DSAParametersGenerator pGen = new DSAParametersGenerator(); pGen.init(512, 80, new SecureRandom()); DSAParameters params = pGen.generateParameters(); DSAKeyGenerationParameters genParam = new DSAKeyGenerationParameters(new SecureRandom(), params); kpg.init(genParam); AsymmetricCipherKeyPair pair = kpg.generateKeyPair(); privKey = (AsymmetricKeyParameter)pair.getPrivate(); pubKey = (AsymmetricKeyParameter)pair.getPublic(); // // distinguished name table. // X500NameBuilder builder = createStdBuilder(); // // extensions // // // create the certificate - version 3 // AlgorithmIdentifier sigAlgId = sigAlgFinder.find("SHA1withDSA"); AlgorithmIdentifier digAlgId = digAlgFinder.find(sigAlgId); ContentSigner sigGen = new BcDSAContentSignerBuilder(sigAlgId, digAlgId).build(privKey); X509v3CertificateBuilder certGen = new BcX509v3CertificateBuilder(builder.build(),BigInteger.valueOf(1),new Date(System.currentTimeMillis() - 50000),new Date(System.currentTimeMillis() + 50000),builder.build(),pubKey); X509CertificateHolder cert = certGen.build(sigGen); assertTrue(cert.isValidOn(new Date())); assertTrue(cert.isSignatureValid(new BcDSAContentVerifierProviderBuilder(digAlgFinder).build(pubKey))); // // create the certificate - version 1 // sigAlgId = sigAlgFinder.find("SHA1withDSA"); digAlgId = digAlgFinder.find(sigAlgId); sigGen = new BcDSAContentSignerBuilder(sigAlgId, digAlgId).build(privKey); X509v1CertificateBuilder certGen1 = new BcX509v1CertificateBuilder(builder.build(),BigInteger.valueOf(1),new Date(System.currentTimeMillis() - 50000),new Date(System.currentTimeMillis() + 50000),builder.build(),pubKey); cert = certGen1.build(sigGen); assertTrue(cert.isValidOn(new Date())); assertTrue(cert.isSignatureValid(new BcDSAContentVerifierProviderBuilder(digAlgFinder).build(pubKey))); ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded()); CertificateFactory fact = CertificateFactory.getInstance("X.509"); X509Certificate x509cert = (X509Certificate)fact.generateCertificate(bIn); //System.out.println(cert); }
private void nullPointerTest() throws Exception { AsymmetricCipherKeyPairGenerator kpg = new RSAKeyPairGenerator(); RSAKeyGenerationParameters genParam = new RSAKeyGenerationParameters( BigInteger.valueOf(0x1001), new SecureRandom(), 1024, 25); kpg.init(genParam); AsymmetricCipherKeyPair kp = kpg.generateKeyPair(); ExtensionsGenerator extGen = new ExtensionsGenerator(); extGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); extGen.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign)); BcX509ExtensionUtils extUtils = new BcX509ExtensionUtils(new SHA1DigestCalculator()); SubjectKeyIdentifier subjectKeyIdentifier = extUtils.createSubjectKeyIdentifier(kp.getPublic()); extGen.addExtension(Extension.subjectKeyIdentifier, false, subjectKeyIdentifier); DefaultSignatureAlgorithmIdentifierFinder sigAlgFinder = new DefaultSignatureAlgorithmIdentifierFinder(); DefaultDigestAlgorithmIdentifierFinder digAlgFinder = new DefaultDigestAlgorithmIdentifierFinder(); AlgorithmIdentifier sigAlgId = sigAlgFinder.find("SHA1withRSA"); AlgorithmIdentifier digAlgId = digAlgFinder.find(sigAlgId); BcContentSignerBuilder contentSignerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId); PKCS10CertificationRequest p1 = new BcPKCS10CertificationRequestBuilder( new X500Name("cn=csr"), kp.getPublic()) .addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate()) .build(contentSignerBuilder.build(kp.getPrivate())); PKCS10CertificationRequest p2 = new BcPKCS10CertificationRequestBuilder( new X500Name("cn=csr"), kp.getPublic()) .addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate()) .build(contentSignerBuilder.build(kp.getPrivate())); if (!p1.equals(p2)) { fail("cert request comparison failed"); } Attribute[] attr1 = p1.getAttributes(); Attribute[] attr2 = p1.getAttributes(); checkAttrs(1, attr1, attr2); attr1 = p1.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest); attr2 = p1.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest); checkAttrs(1, attr1, attr2); }
/** * Create a key pair generator for the given <b>asymmetric</b> encryption algorithm. If <code>initWithDefaults</code> * is specified with value <code>true</code>, the returned generator is ready to be used and doesn't require any * further initialisation. * * @param algorithmName the name of the <b>asymmetric</b> encryption algorithm. This is the first element of a transformation, i.e. * you can pass a <code>transformation</code> to {@link #splitTransformation(String)} and use element 0 of its result. * See <a target="_blank" href="http://cumulus4j.org/${project.version}/documentation/supported-algorithms.html">Supported algorithms</a> * for a list of supported algorithms. * @param initWithDefaults whether to initialise the key pair generator with default values. * @return an instance of {@link AsymmetricCipherKeyPairGenerator}. If <code>initWithDefaults == true</code>, it can directly * be used to generate key pairs, i.e. it is already initialised with some default values. If <code>initWithDefaults == false</code>, * you still have to {@link AsymmetricCipherKeyPairGenerator#init(org.bouncycastle.crypto.KeyGenerationParameters) initialise} the * key pair generator before you can use it. * @throws NoSuchAlgorithmException if there is no generator available for the given <code>algorithmName</code>. */ public AsymmetricCipherKeyPairGenerator createKeyPairGenerator(final String algorithmName, final boolean initWithDefaults) throws NoSuchAlgorithmException { if (algorithmName == null) throw new IllegalArgumentException("algorithmName == null"); final AsymmetricCipherKeyPairGeneratorFactory factory = algorithmName2asymmetricCipherKeyPairGeneratorFactory.get(algorithmName); if (factory == null) throw new NoSuchAlgorithmException("There is no key-pair-generator-class registered for algorithmName \"" + algorithmName + "\"!"); final AsymmetricCipherKeyPairGenerator generator = factory.createAsymmetricCipherKeyPairGenerator(initWithDefaults); return generator; }
/** * Create and optionally initialise a new instance of {@link AsymmetricCipherKeyPairGenerator}. * @param initWithDefaults whether to * {@link AsymmetricCipherKeyPairGenerator#init(org.bouncycastle.crypto.KeyGenerationParameters) initialise} the <code>AsymmetricCipherKeyPairGenerator</code> with default values * so that it can be used immediately as-is. * @return a new instance of {@link AsymmetricCipherKeyPairGenerator} (iff <code>initWithDefaults==true</code> ready-to-use; * otherwise requiring {@link AsymmetricCipherKeyPairGenerator#init(org.bouncycastle.crypto.KeyGenerationParameters) initialisation} * before it can be used). */ AsymmetricCipherKeyPairGenerator createAsymmetricCipherKeyPairGenerator(boolean initWithDefaults);