Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing the private-key/public-certificate pair in the Java KeyStore [duplicate]

I used the following steps to create a new Java keystore with a pair of private/public key to be used by a Java (internal) server with TLS. Please notice that the certificate is selfsigned:

1) Generate key with AES256

openssl genrsa -aes256 -out server.key 1024 

2) Generate cert request for CA

openssl req -x509 -sha256 -new -key server.key -out server.csr 

3) Generate self signed expiry-time 10 years

openssl x509 -sha256 -days 3652 -in server.csr -signkey server.key -out selfsigned.crt 

4) Use a program like KeyStoreExplorer to import the pair (private key and selfsigned certificate) in a new JKS

This works but I'd like to implement the last step without using a GUI.

I know how to import the self signed certificate only:

// create the keystore and import the public key. THIS WILL NOT IMPORT THE PRIVATE KEY SO THE KEYSTORE CAN'T BE USED ON THE SERVER TO MAKE THE TLS CONNECTION /usr/java/jdk1.6.0_45/bin/keytool -import -alias myservercert -file server.crt -keystore mykeystore.jks 

So the question is: how can I create a Java KeyStore and import both the certificate with the public key and the private key without using a GUI?

like image 346
kingston Avatar asked Jul 17 '13 08:07

kingston


People also ask

Can you import a private key into keystore?

You can't directly import private key information to a keystore (. JKS) using keytool. Instead, you must convert the certificate and private key into a PKCS 12 (. p12) file, and then you can import the PKCS 12 file into your keystore.

How do I import a private key certificate?

Navigate to Personal | Certificates pane. Right-click within the Certificates panel and click All Tasks | Import to start the Certificate Import Wizard. Follow the wizard to import the signed certificate along with the private key.


1 Answers

With your private key and public certificate, you need to create a PKCS12 keystore first, then convert it into a JKS.

# Create PKCS12 keystore from private key and public certificate. openssl pkcs12 -export -name myservercert -in selfsigned.crt -inkey server.key -out keystore.p12  # Convert PKCS12 keystore into a JKS keystore keytool -importkeystore -destkeystore mykeystore.jks -srckeystore keystore.p12 -srcstoretype pkcs12 -alias myservercert 

To verify the contents of the JKS, you can use this command:

keytool -list -v -keystore mykeystore.jks 

If this was not a self-signed certificate, you would probably want to follow this step with importing the certificate chain leading up to the trusted CA cert.

like image 90
gtrig Avatar answered Oct 22 '22 13:10

gtrig