KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA", "BC");
gen.initialize(1024, new SecureRandom());
KeyPair pair = gen.generateKeyPair();
RSAPrivateKey privKey = (RSAPrivateKey)pair.getPrivate();
RSAPublicKey pubKey = (RSAPublicKey)pair.getPublic();
BigInteger modulus = privKey.getModulus();
BigInteger privateExponent = privKey.getPrivateExponent();
//
// distinguished name table.
//
Hashtable attrs = new Hashtable();
Vector order = new Vector();
attrs.put(X509Principal.C, "AU");
attrs.put(X509Principal.O, "The Legion of the Bouncy Castle");
attrs.put(X509Principal.L, "Melbourne");
attrs.put(X509Principal.ST, "Victoria");
attrs.put(X509Principal.EmailAddress, "feedback-crypto@bouncycastle.org");
order.addElement(X509Principal.C);
order.addElement(X509Principal.O);
order.addElement(X509Principal.L);
order.addElement(X509Principal.ST);
order.addElement(X509Principal.EmailAddress);
//
// extensions
//
//
// create the certificate.
//
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(1));
certGen.setIssuerDN(new X509Principal(order, attrs));
certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000));
certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
certGen.setSubjectDN(new X509Principal(order, attrs));
certGen.setPublicKey(pubKey);
certGen.setSignatureAlgorithm("MD5WithRSAEncryption");
Certificate[] chain = new Certificate[1];
try
{
X509Certificate cert = certGen.generate(privKey);
cert.checkValidity(new Date());
cert.verify(pubKey);
ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded());
CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");
cert = (X509Certificate)fact.generateCertificate(bIn);
chain[0] = cert;
}
catch (Exception e)
{
fail("error generating cert - " + e.toString());
}
store.setKeyEntry("private", privKey, passwd, chain);
//
// write out and read back store
//
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
store.store(bOut, passwd);
ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray());
//
// start with a new key store
//
store = KeyStore.getInstance(storeName, "BC");
store.load(bIn, passwd);
//
// verify public key
//
privKey = (RSAPrivateKey)store.getKey("private", passwd);
if (!privKey.getModulus().equals(modulus))
{
fail("private key modulus wrong");
}
else if (!privKey.getPrivateExponent().equals(privateExponent))
{
fail("private key exponent wrong");
}
//