76

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?

4

2 回答 2

182

使用您的私钥和公共证书,您需要先创建一个 PKCS12 密钥库,然后将其转换为 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

要验证 JKS 的内容,可以使用以下命令:

keytool -list -v -keystore mykeystore.jks

如果这不是自签名证书,您可能希望按照此步骤导入导致受信任 CA 证书的证书链。

于 2013-07-17T21:31:03.923 回答
0

密钥库需要一个密钥库文件。该类KeyStore需要一个FileInputStream. 但是,如果您提供 null (而不是FileInputStream实例),则会加载一个空的密钥库。创建密钥库后,您可以使用keytool.

以下代码使用空密码创建一个空密钥库

  KeyStore ks2 = KeyStore.getInstance("jks");
  ks2.load(null,"".toCharArray());
  FileOutputStream out = new FileOutputStream("C:\\mykeytore.keystore");
  ks2.store(out, "".toCharArray());

拥有密钥库后,导入证书非常容易。查看此链接以获取示例代码。

于 2013-07-17T09:34:14.350 回答