1

How can I insert a key pair into a key store using Java? I want to do exactly what this keytool command does, but using Java:

keytool -genkeypair -alias keyRSA -keyalg RSA -keysize 2048 -storetype JCEKS -keystore .keystore

When executing this command it asks for certificate details like:

  • What is your first and last Name?
  • What is the name of your the organizational unit?
  • What is the name of your organization?
  • ...

I want to set those certificate details using java. The certificate format is X509

Java code below

File keyStoreFile = new File(".keystore");
KeyStore keyStore = KeyStore.getInstance("JCEKS");

//Create empty keystore
keyStore.load(null, null);
keyStore.store(new FileOutputStream(keyStoreFile), "12345".toCharArray());

//Get keyPair from somewhere
KeyPair keyPair = ...

//HOW TO GET CERTIFICATE?
Certificate[] chain = ... ???

//Insert key pair entry into key store
keyStore.setKeyEntry("keyRSA", keyPair.getPrivate(), "12345".toCharArray(), certificateChain);
keyStore.store(new FileOutputStream(keyStoreFile), "12345".toCharArray());
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Andre Proenza
  • 149
  • 1
  • 10
  • You can't with Java alone. You need a third-party JCE implementation such as BouncyCastle. But why are you doing this? Who is going to trust this certificate? – user207421 Mar 28 '21 at 05:33
  • @user207421: I'm sorry to regret but **you can** store RSA keys with native Java (without 3rd party tools). Kindly see my answer https://stackoverflow.com/a/64443753/8166854 to find a full working implementation to generate a **self signed certificate** and save it along the RSA key pair in a PKCS12 keystore. One thing to note: it uses SUN dependencies that may not available on all Java JDK's (tested on OpenJava 11). – Michael Fehr Mar 28 '21 at 07:25
  • @MichaelFehr The question is about creating certificates, not 'stor[ing] RSA keys', which the OP is already doing here, and you can't create certificates in 100% pure Java. I'm aware of the SUN classes, having used them in 1998, but this has never been a viable solution. – user207421 Mar 29 '21 at 05:58
  • @user207421: you are right - you need to create a (self signed) certificate to store a private key / key pair in a key store. That's why my linked solution generates a certificate with the help of SUN classes. If you are aware of the SUN classes then you have to be aware as well to Java's keytool as it bases on exact those classes. A (very more) elegant version is possible by using Bouncy Castle. – Michael Fehr Mar 29 '21 at 11:17

0 Answers0