How to create X509 certificate using Java?

I want to create an X509 certificate using the Java language and then extract the public key from it.

I searched the Internet and found many code examples, but all of them have errors (unknown variable or unknown type) or there are many warnings that say something like: "method ... from type ... deprecated", etc.

For example, why the following code does not work:

PublicKey pk; CertificateFactory cf = CertificateFactory.getInstance("X.509"); String PKstr = pk.toString(); InputStream PKstream = new ByteArrayInputStream(PKstr.getBytes()); X509Certificate pkcert = (X509Certificate)cf.generateCertificate(PKstream); 


Can someone show me how to create a certificate using pure Java or Bouncy Castle and then get the public key from it?

Thanks to everyone.

+7
source share
2 answers

You can also create a certificate using only the JDK classes. The downside is that you have to use two classes from the sun.security.x509 package. The code will look like this:

 KeyStore keyStore = ... // your keystore // generate the certificate // first parameter = Algorithm // second parameter = signrature algorithm // third parameter = the provider to use to generate the keys (may be null or // use the constructor without provider) CertAndKeyGen certGen = new CertAndKeyGen("RSA", "SHA256WithRSA", null); // generate it with 2048 bits certGen.generate(2048); // prepare the validity of the certificate long validSecs = (long) 365 * 24 * 60 * 60; // valid for one year // add the certificate information, currently only valid for one year. X509Certificate cert = certGen.getSelfCertificate( // enter your details according to your application new X500Name("CN=My Application,O=My Organisation,L=My City,C=DE"), validSecs); // set the certificate and the key in the keystore keyStore.setKeyEntry(certAlias, certGen.getPrivateKey(), null, new X509Certificate[] { cert }); 

Get the secret key from the keystore to encrypt or decrypt data. Based on the code is http://www.pixelstech.net/article/1408524957-Generate-cetrificate-in-Java----3

+16
source

Yes, with BouncyCastle, creating an X509 certificate from 2 public keys (a key for the certificate and one for the CA) is executed here .

I turn the resulting certificate into PEM here .

+5
source

All Articles