Reputation: 329
How do I create a X509Certificate to my KeyPair? (My class already has the KeyPair and I need to create a certificate which will hold my public key and then store it on a keystore).
I was expecting to have a X509Certificate constructor able to receive my public key and then store it through keystore.setEntry( pvtkey, cert) but I didnt find nothing useful to associate the new certificate and my key pair...
Any idea?
Edit: I also tried to pass certificate chain as null but it doesn't work, it looks like a bug reported on https://bugs.java.com/bugdatabase/view_bug;jsessionid=5866fda73ac1258fcfebef9c3234?bug_id=4906869
Thanks!
Upvotes: 2
Views: 3554
Reputation: 175
Here is a related question with solution how to generate self-signed X509Certificate: link
Try to use BouncyCastle classes in this way:
// generate a key pair
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
keyPairGenerator.initialize(4096, new SecureRandom());
KeyPair keyPair = keyPairGenerator.generateKeyPair();
// build a certificate generator
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
X500Principal dnName = new X500Principal("cn=Example_CN");
// add some options
certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
certGen.setSubjectDN(new X509Name("dc=Example_Name"));
certGen.setIssuerDN(dnName); // use the same
// yesterday
certGen.setNotBefore(new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000));
// in 2 years
certGen.setNotAfter(new Date(System.currentTimeMillis() + 2 * 365 * 24 * 60 * 60 * 1000));
certGen.setPublicKey(keyPair.getPublic());
certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_timeStamping));
// finally, sign the certificate with the private key of the same KeyPair
X509Certificate cert = certGen.generate(keyPair.getPrivate(), "BC");
Remember to add Security Provider:
Security.addProvider(new BouncyCastleProvider());
Upvotes: 1
Reputation: 42009
There is no Java class in Oracle Java to create an X509Certificate. You either have to
EDIT :
As these entries can stay around for quite some time, I should add that the above statements apply to Java 7 and earlier.
Upvotes: 3