1. 程式人生 > >用OpenSSL建立CA和簽發證書,轉換成java可以載入的jks

用OpenSSL建立CA和簽發證書,轉換成java可以載入的jks

java的keytool工具本來就可以生成互動式認證的證書, 不過其他語言處理互動式認證的流程貌似和java的keytool的認證流程有些差別,  而openssl是比較通用的工具。大部分語言都會支援openssl生成的證書檔案。用openssl簽發的證書如何才能轉化為keytool的jks檔案呢,  就需要用到 ImportKey.java 檔案的原始碼來處理了。

 - CAserial 指明序列號檔案,而 - CAcreateserial 指明檔案不存在時自動生成

 所有證書的Common Name 也就是CN不能重複

----------------------------------START--------------------------------
CA根證書
openssl genrsa -out ca.key 2048
openssl req -x509 -new -nodes -key ca.key -subj "/CN=ABC" -days 36500 -out ca.crt
openssl pkcs12 -export -clcerts -in ./ca.crt -inkey ca.key -out ca.p12

伺服器端:
openssl genrsa -out Xserver.key 2048
openssl req -new -key Xserver.key -subj "/CN=DEF" -out Xserver.csr
openssl x509 -req -days 36500 -in Xserver.csr -CA ca.crt -CAkey ca.key -CAcreateserial  -out Xserver.crt

cp  Xserver.key  Xserver.key.pem
cp  Xserver.crt  Xserver.crt.pem

openssl 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 2048
openssl req -new -key XBrowser.key -subj "/CN=XXX" -out XBrowser.csr
openssl 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 key
  • generate a Certificate Signung Request (CSR) for the private key in this JKS
  • import 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 DER
openssl 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

[email protected]:~$ java ImportKey key.der cert.der
Using keystore-file : /home/user/keystore.ImportKey
One 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.