首页 > 学院 > 开发设计 > 正文

用OpenSSL创建CA和签发证书,转换成java可以加载的jks

2019-11-14 11:08:31
字体:
来源:转载
供稿:网友

java的keytool工具本来就可以生成交互式认证的证书, 不过其他语言处理交互式认证的流程貌似和java的keytool的认证流程有些差别,  而openssl是比较通用的工具。大部分语言都会支持openssl生成的证书文件。用openssl签发的证书如何才能转化为keytool的jks文件呢,  就需要用到 ImportKey.java 文件的源码来处理了。

 - CAserial 指明序列号文件,而 - CAcreateserial 指明文件不存在时自动生成

 所有证书的Common Name 也就是CN不能重复

----------------------------------START--------------------------------CA根证书openssl genrsa -out ca.key 2048openssl req -x509 -new -nodes -key ca.key -subj "/CN=ABC" -days 36500 -out ca.crtopenssl pkcs12 -export -clcerts -in ./ca.crt -inkey ca.key -out ca.p12服务器端:openssl genrsa -out Xserver.key 2048openssl req -new -key Xserver.key -subj "/CN=DEF" -out Xserver.csropenssl x509 -req -days 36500 -in Xserver.csr -CA ca.crt -CAkey ca.key -CAcreateserial  -out Xserver.crtcp  Xserver.key  Xserver.key.pemcp  Xserver.crt  Xserver.crt.pemopenssl pkcs8 -topk8 -nocrypt -in Xserver.key.pem -inform PEM -out Xserver.key.der -outform DER openssl x509 -in Xserver.crt.pem -inform PEM -out Xserver.crt.der -outform DER 生成 jks文件给java程序使用java -jar  OpenSSL2JKS.jar  Xserver.key.der   Xserver.crt.der  123456  ./server.keystore server_jks创建信任列表keytool -import -v -alias rootca -keystore ./serverTrust.jks -storepass 123456  -trustcacerts -file ./ca.crt keytool -import -v -alias server -keystore ./serverTrust.jks -storepass 123456  -trustcacerts -file ./client.services-ca.pem生成浏览器证书openssl genrsa -out XBrowser.key 2048openssl req -new -key XBrowser.key -subj "/CN=XXX" -out XBrowser.csropenssl x509 -req -days 36500 -in XBrowser.csr -CA ca.crt -CAkey ca.key -CAcreateserial  -out XBrowser.crt把浏览器证书转化为PKCS12格式openssl pkcs12 -export -clcerts -in ./XBrowser.crt -inkey XBrowser.key -out XBrowser.p12用openssl自带的工具进行测试openssl s_client -connect www.tesladevel.com:9999 -cert ./XBrowser.crt -key ./XBrowser.key  -tls1 -CAfile ./ca.crt  -state -showcerts------------------------------------------END--------------------------------------------------

上面用到的  OpenSSL2JKS.jar , 其实是  ImportKey.java 文件 ,

下载地址如下:

www.agentbob.info/agentbob/80/version/default/part/AttachmentData/data/ImportKey.java

我把这个文件的源码贴出来:

package com.tool;import java.security.*;import java.io.IOException;import java.io.InputStream;import java.io.FileInputStream;import java.io.DataInputStream;import java.io.ByteArrayInputStream;import java.io.FileOutputStream;import java.security.spec.*;import java.security.cert.Certificate;import java.security.cert.CertificateFactory;import java.util.Collection;import java.util.Iterator;/** * ImportKey.java * * <p>This class imports a key and a certificate into a keystore * (<code>$home/keystore.ImportKey</code>). If the keystore is * already PResent, it is simply deleted. Both the key and the * certificate file must be in <code>DER</code>-format. The key must be * encoded with <code>PKCS#8</code>-format. The certificate must be * encoded in <code>X.509</code>-format.</p> * * <p>Key format:</p> * <p><code>openssl pkcs8 -topk8 -nocrypt -in YOUR.KEY -out YOUR.KEY.der * -outform der</code></p> * <p>Format of the certificate:</p> * <p><code>openssl x509 -in YOUR.CERT -out YOUR.CERT.der -outform * der</code></p> * <p>Import key and certificate:</p> * <p><code>java comu.ImportKey YOUR.KEY.der YOUR.CERT.der</code></p><br /> * * <p><em>Caution:</em> the old <code>keystore.ImportKey</code>-file is * deleted and replaced with a keystore only containing <code>YOUR.KEY</code> * and <code>YOUR.CERT</code>. The keystore and the key has no passWord;  * they can be set by the <code>keytool -keypasswd</code>-command for setting * the key password, and the <code>keytool -storepasswd</code>-command to set * the keystore password. * <p>The key and the certificate is stored under the alias * <code>importkey</code>; to change this, use <code>keytool -keyclone</code>. * * Created: Fri Apr 13 18:15:07 2001 * Updated: Fri Apr 19 11:03:00 2002 * * @author Joachim Karrer, Jens Carlberg * @version 1.1 **/public class ImportKey  {        /**     * <p>Creates an InputStream from a file, and fills it with the complete     * file. Thus, available() on the returned InputStream will return the     * full number of bytes the file contains</p>     * @param fname The filename     * @return The filled InputStream     * @exception IOException, if the Streams couldn't be created.     **/    private static InputStream fullStream ( String fname ) throws IOException {        FileInputStream fis = new FileInputStream(fname);        DataInputStream dis = new DataInputStream(fis);        byte[] bytes = new byte[dis.available()];        dis.readFully(bytes);        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);        return bais;    }            /**     * <p>Takes two file names for a key and the certificate for the key,      * and imports those into a keystore. Optionally it takes an alias     * for the key.     * <p>The first argument is the filename for the key. The key should be     * in PKCS8-format.     * <p>The second argument is the filename for the certificate for the key.     * <p>If a third argument is given it is used as the alias. If missing,     * the key is imported with the alias importkey     * <p>The name of the keystore file can be controlled by setting     * the keystore property (java -Dkeystore=mykeystore). If no name     * is given, the file is named <code>keystore.ImportKey</code>     * and placed in your home directory.     * @param args [0] Name of the key file, [1] Name of the certificate file     * [2] Alias for the key.     **/    public static void main ( String args[]) {                // change this if you want another password by default        String keypass = "importkey";                // change this if you want another alias by default        String defaultalias = "importkey";        // change this if you want another keystorefile by default        String keystorename = System.getProperty("keystore");        if (keystorename == null)            keystorename = System.getProperty("user.home")+  System.getProperty("file.separator")+ "keystore.ImportKey"; // especially this ;-)        // parsing command line input        String keyfile = "";        String certfile = "";        if (args.length < 2 || args.length>5) {            System.out.println("Usage: java comu.ImportKey keyfile certfile keypass keystorename [alias]");            System.exit(0);        } else {            keyfile = args[0];            certfile = args[1];            keypass = args[2];            keystorename = args[3];                        if (args.length>4)                defaultalias = args[4];        }        try {            // initializing and clearing keystore             KeyStore ks = KeyStore.getInstance("JKS", "SUN");            ks.load( null , keypass.toCharArray());            System.out.println("Using keystore-file : "+keystorename);            ks.store(new FileOutputStream ( keystorename  ),  keypass.toCharArray());            ks.load(new FileInputStream ( keystorename ),  keypass.toCharArray());            // loading Key            InputStream fl = fullStream (keyfile);            byte[] key = new byte[fl.available()];            KeyFactory kf = KeyFactory.getInstance("RSA");            fl.read ( key, 0, fl.available() );            fl.close();            PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec ( key );            PrivateKey ff = kf.generatePrivate (keysp);            // loading CertificateChain            CertificateFactory cf = CertificateFactory.getInstance("X.509");            InputStream certstream = fullStream (certfile);            Collection c = cf.generateCertificates(certstream) ;            Certificate[] certs = new Certificate[c.toArray().length];            if (c.size() == 1) {                certstream = fullStream (certfile);                System.out.println("One certificate, no chain.");                Certificate cert = cf.generateCertificate(certstream) ;                certs[0] = cert;            } else {                System.out.println("Certificate chain length: "+c.size());                certs = (Certificate[])c.toArray();            }            // storing keystore            ks.setKeyEntry(defaultalias, ff, keypass.toCharArray(), certs );            System.out.println ("Key and certificate stored.");            System.out.println ("Alias:"+defaultalias+"  Password:"+keypass);            ks.store(new FileOutputStream ( keystorename ), keypass.toCharArray());        } catch (Exception ex) {            ex.printStackTrace();        }    }}// KeyStore

Import private key and certificate into Java Key Store (JKS)

Apache Tomcat and many other Java applications expect to retrieve SSL/TLScertificates from a Java Key Store (JKS). Jave Virtual Machines usually comewithkeytool to help you create a new key store.

Keytool helps you to:

create a new JKS with a new private keygenerate a Certificate Signung Request (CSR) for the private key in this JKSimport a certificate that you received for this CSR into your JKS

Keytool does not let you import an existing private key forwhich you already have a certificate. So you need to do this yourself, here'show:

Let's assume you have a private key (key.pem) and acertificate (cert.pem), both in PEM format as the file namessuggest.

PEM format is 'kind-of-human-readable' and looks like e.g.

-----BEGIN CERTIFICATE-----Ulv6GtdFbjzLeqlkelqwewlq822OrEPdH+zxKUkKGX/eN.. (snip).9801asds3BCfu52dm7JHzPAOqWKaEwIgymlk=----END CERTIFICATE-----

Convert both, the key and the certificate into DER format usingopenssl :

openssl pkcs8 -topk8 -nocrypt -in key.pem -inform PEM -out key.der -outform DERopenssl x509 -in cert.pem -inform PEM -out cert.der -outform DER

Now comes the tricky bit, you need something to import these files into theJKS. ImportKey will do this for you, get theImportKey.java (text/x-java-source, 6.6 kB, info) source or the compiled (Java 1.5 !)ImportKey.class (application/octet-stream, 3.3 kB, info) and run it like

user@host:~$ java ImportKey key.der cert.derUsing keystore-file : /home/user/keystore.ImportKeyOne certificate, no chain.Key and certificate stored.Alias:importkey  Password:importkey

Now we have a proper JKS containing our private key and certificate in a filecalled keystore.ImportKey, using 'importkey' as alias and also as password. Forany further changes, like changing the password we can use keytool.

http://stackoverflow.com/questions/723368/how-to-use-pem-file-to-create-a-ssl-socket-in-java


上一篇:Java-FastJson

下一篇:abp项目之旅

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表