将PEM导入Java密钥库


144

我正在尝试连接到SSL服务器,这需要我进行身份验证。为了在Apache MINA上使用SSL,我需要一个合适的JKS文件。但是,我只得到了一个.PEM文件。

如何从PEM文件创建JKS文件?


1
可能此链接可能会有所帮助:http
Laurent K 2010年

Answers:


235

首先,将您的证书转换为DER格式:

openssl x509 -outform der -in certificate.pem -out certificate.der

然后,将其导入密钥库中:

keytool -import -alias your-alias -keystore cacerts -file certificate.der

7
如果.pem文件包含多个证书,则该证书不起作用。
MarioVilas 2014年

14
我只有一个.pem证书,这不起作用。1795:错误:0906D06C:PEM例程:PEM_read_bio:无起始行:/ usr / src / secure / lib / libcrypto /../../../ crypto / openssl / crypto / pem / pem_lib.c:648:正在检查:可信证书
Brian Knoblauch 2014年

4
我找到了解决方案。将根证书和中间证书预先附加到.pem,然后进行转换。
Brian Knoblauch 2014年

1
@Anthony此命令仅告诉您如何将PEM导入JKS。添加用于从商店导出JKS的命令可能是一个好主意。
Vishal Biyani

2
如果.pem上有多个证书,如何导入Java密钥库?
Erick

55

如果您只想将PEM格式的证书导入密钥库,则keytool将完成此工作:

keytool -import -alias *alias* -keystore cacerts -file *cert.pem*

11
如果我这样走,我得到一个错误:keytool错误:java.lang.Exception:输入的不是X.509证书
frandevel 2012年

1
@frandevel,此错误可能是由于PEM输入文件的标题高于--- BEGIN分隔符或在一个文件中包含多个PEM或两者引起的。要么一次删除所有无关数据,然后一次输入每个PEM,要么使用我的工具,如我的答案中所述。
Alastair McCormack

感谢@Fuzzyfelt,我来看一下
frandevel

1
同样的问题,.PEM文件干净,带有所有适当的头。
Brian Knoblauch 2014年

17

我已经开发了http://code.google.com/p/java-keyutil/,可将PEM证书直接导入Java密钥库中。其主要目的是导入多部分PEM操作系统证书捆绑包,例如ca-bundle.crt。这些通常包括keytool无法处理的标头

</self promotion>

4
这不是一个不好的玩具项目,但是keytool已经为您(以及更多)完成了所有这一切。(顺便说一句,如果发生异常,则应关闭FileOutputStream,并关闭中的I / O流finally。)
Bruno

8
嗨,布鲁诺,谢谢你的提示。真正的用例是一次性导入/etc/pki/tls/certs/ca-bundle.crt(RHEL / CentOS)的所有条目。AFAIK,keytool将仅导入第一个条目。我已经看到许多人以不同的方式执行此操作,但通常涉及为每个证书多次调用keytool。Ubuntu有一个完全可以执行此操作的更新脚本,只是Ubuntu将其证书存储在目录中。我将在不久的将来添加对目录的支持。再次感谢您检查代码。
Alastair McCormack

14

在我的情况下,我有一个pem文件,其中包含两个证书和一个用于相互SSL身份验证的加密私钥。所以我的pem文件看起来像这样:

-----BEGIN CERTIFICATE-----

...

-----END CERTIFICATE-----

-----BEGIN RSA PRIVATE KEY-----

Proc-Type: 4,ENCRYPTED

DEK-Info: DES-EDE3-CBC,C8BF220FC76AA5F9

...

-----END RSA PRIVATE KEY-----

-----BEGIN CERTIFICATE-----

...

-----END CERTIFICATE-----

这是我所做的

将文件分为三个单独的文件,以便每个文件仅包含一个条目,---BEGIN..---END..行开头和结尾。让我们假设我们现在有三个文件:cert1.pemcert2.pem,和pkey.pem

pkey.pem使用openssl和以下语法转换为DER格式:

openssl pkcs8 -topk8 -nocrypt-输入pkey.pem-通知PEM-输出pkey.der-转换DER

请注意,如果私钥已加密,则需要提供密码(从原始pem文件的供应商处获取)以转换为DER格式, openssl将要求您提供如下密码:“输入密码pkey.pem:”。

如果转换成功,您将获得一个名为的新文件pkey.der

创建一个新的Java密钥库,并导入私钥和证书:

String keypass = "password";  // this is a new password, you need to come up with to protect your java key store file
String defaultalias = "importkey";
KeyStore ks = KeyStore.getInstance("JKS", "SUN");

// this section does not make much sense to me, 
// but I will leave it intact as this is how it was in the original example I found on internet:   
ks.load( null, keypass.toCharArray());
ks.store( new FileOutputStream ( "mykeystore"  ), keypass.toCharArray());
ks.load( new FileInputStream ( "mykeystore" ),    keypass.toCharArray());
// end of section..


// read the key file from disk and create a PrivateKey

FileInputStream fis = new FileInputStream("pkey.der");
DataInputStream dis = new DataInputStream(fis);
byte[] bytes = new byte[dis.available()];
dis.readFully(bytes);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);

byte[] key = new byte[bais.available()];
KeyFactory kf = KeyFactory.getInstance("RSA");
bais.read(key, 0, bais.available());
bais.close();

PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec ( key );
PrivateKey ff = kf.generatePrivate (keysp);


// read the certificates from the files and load them into the key store:

Collection  col_crt1 = CertificateFactory.getInstance("X509").generateCertificates(new FileInputStream("cert1.pem"));
Collection  col_crt2 = CertificateFactory.getInstance("X509").generateCertificates(new FileInputStream("cert2.pem"));

Certificate crt1 = (Certificate) col_crt1.iterator().next();
Certificate crt2 = (Certificate) col_crt2.iterator().next();
Certificate[] chain = new Certificate[] { crt1, crt2 };

String alias1 = ((X509Certificate) crt1).getSubjectX500Principal().getName();
String alias2 = ((X509Certificate) crt2).getSubjectX500Principal().getName();

ks.setCertificateEntry(alias1, crt1);
ks.setCertificateEntry(alias2, crt2);

// store the private key
ks.setKeyEntry(defaultalias, ff, keypass.toCharArray(), chain );

// save the key store to a file         
ks.store(new FileOutputStream ( "mykeystore" ),keypass.toCharArray());

(可选)验证新密钥库的内容:

$ keytool -list -keystore mykeystore -storepass password

密钥库类型:JKS密钥库提供者:SUN

您的密钥库包含3个条目:

  • cn = ...,ou = ...,o = ..,2014年9月2日,trustCertEntry,证书指纹(SHA1):2C:B8:...

  • importkey,2014年9月2日,PrivateKeyEntry,证书指纹(SHA1):9C:B0:...

  • cn = ...,o = ....,2014年9月2日,trustCertEntry,证书指纹(SHA1):83:63:...

(可选)针对SSL服务器测试新密钥存储中的证书和私钥:(您可能希望将调试作为VM选项启用:-Djavax.net.debug = all)

        char[] passw = "password".toCharArray();
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        ks.load(new FileInputStream ( "mykeystore" ), passw );

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passw);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        TrustManager[] tm = tmf.getTrustManagers();

        SSLContext sclx = SSLContext.getInstance("TLS");
        sclx.init( kmf.getKeyManagers(), tm, null);

        SSLSocketFactory factory = sclx.getSocketFactory();
        SSLSocket socket = (SSLSocket) factory.createSocket( "192.168.1.111", 443 );
        socket.startHandshake();

        //if no exceptions are thrown in the startHandshake method, then everything is fine..

如果打算使用它,最后向HttpsURLConnection注册您的证书:

        char[] passw = "password".toCharArray();
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        ks.load(new FileInputStream ( "mykeystore" ), passw );

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passw);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        TrustManager[] tm = tmf.getTrustManagers();

        SSLContext sclx = SSLContext.getInstance("TLS");
        sclx.init( kmf.getKeyManagers(), tm, null);

        HostnameVerifier hv = new HostnameVerifier()
        {
            public boolean verify(String urlHostName, SSLSession session)
            {
                if (!urlHostName.equalsIgnoreCase(session.getPeerHost()))
                {
                    System.out.println("Warning: URL host '" + urlHostName + "' is different to SSLSession host '" + session.getPeerHost() + "'.");
                }
                return true;
            }
        };

        HttpsURLConnection.setDefaultSSLSocketFactory( sclx.getSocketFactory() );
        HttpsURLConnection.setDefaultHostnameVerifier(hv);

您的主机名验证程序是错误的,session.getPeerHost()没有返回证书中的名称,而是您与之连接的名称(即urlHostName此处),因此这总是正确的。true反正你总是回来。
布鲁诺

9

如果您需要一种简单的方法来用Java加载PEM文件而无需使用外部工具(opensll,keytool),这是我在生产环境中使用的代码:

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocketFactory;
import javax.xml.bind.DatatypeConverter;

public class PEMImporter {

    public static SSLServerSocketFactory createSSLFactory(File privateKeyPem, File certificatePem, String password) throws Exception {
        final SSLContext context = SSLContext.getInstance("TLS");
        final KeyStore keystore = createKeyStore(privateKeyPem, certificatePem, password);
        final KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(keystore, password.toCharArray());
        final KeyManager[] km = kmf.getKeyManagers();
        context.init(km, null, null);
        return context.getServerSocketFactory();
    }

    /**
     * Create a KeyStore from standard PEM files
     * 
     * @param privateKeyPem the private key PEM file
     * @param certificatePem the certificate(s) PEM file
     * @param the password to set to protect the private key
     */
    public static KeyStore createKeyStore(File privateKeyPem, File certificatePem, final String password)
            throws Exception, KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
        final X509Certificate[] cert = createCertificates(certificatePem);
        final KeyStore keystore = KeyStore.getInstance("JKS");
        keystore.load(null);
        // Import private key
        final PrivateKey key = createPrivateKey(privateKeyPem);
        keystore.setKeyEntry(privateKeyPem.getName(), key, password.toCharArray(), cert);
        return keystore;
    }

    private static PrivateKey createPrivateKey(File privateKeyPem) throws Exception {
        final BufferedReader r = new BufferedReader(new FileReader(privateKeyPem));
        String s = r.readLine();
        if (s == null || !s.contains("BEGIN PRIVATE KEY")) {
            r.close();
            throw new IllegalArgumentException("No PRIVATE KEY found");
        }
        final StringBuilder b = new StringBuilder();
        s = "";
        while (s != null) {
            if (s.contains("END PRIVATE KEY")) {
                break;
            }
            b.append(s);
            s = r.readLine();
        }
        r.close();
        final String hexString = b.toString();
        final byte[] bytes = DatatypeConverter.parseBase64Binary(hexString);
        return generatePrivateKeyFromDER(bytes);
    }

    private static X509Certificate[] createCertificates(File certificatePem) throws Exception {
        final List<X509Certificate> result = new ArrayList<X509Certificate>();
        final BufferedReader r = new BufferedReader(new FileReader(certificatePem));
        String s = r.readLine();
        if (s == null || !s.contains("BEGIN CERTIFICATE")) {
            r.close();
            throw new IllegalArgumentException("No CERTIFICATE found");
        }
        StringBuilder b = new StringBuilder();
        while (s != null) {
            if (s.contains("END CERTIFICATE")) {
                String hexString = b.toString();
                final byte[] bytes = DatatypeConverter.parseBase64Binary(hexString);
                X509Certificate cert = generateCertificateFromDER(bytes);
                result.add(cert);
                b = new StringBuilder();
            } else {
                if (!s.startsWith("----")) {
                    b.append(s);
                }
            }
            s = r.readLine();
        }
        r.close();

        return result.toArray(new X509Certificate[result.size()]);
    }

    private static RSAPrivateKey generatePrivateKeyFromDER(byte[] keyBytes) throws InvalidKeySpecException, NoSuchAlgorithmException {
        final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
        final KeyFactory factory = KeyFactory.getInstance("RSA");
        return (RSAPrivateKey) factory.generatePrivate(spec);
    }

    private static X509Certificate generateCertificateFromDER(byte[] certBytes) throws CertificateException {
        final CertificateFactory factory = CertificateFactory.getInstance("X.509");
        return (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(certBytes));
    }

}

玩得开心。


问题是关于“基于Apache MINA的SSL”,它可以通过提供的“ PEMs函数提供的SSLServerSocketFactory”进行配置,请参见mina.apache.org/mina-project/userguide/ch11-ssl-filter/…
BluEOS

8

我总是忘记如何执行此操作,因为这是我偶尔执行的操作,这是一种可能的解决方案,并且它可以正常工作:

  1. 转到您喜欢的浏览器,然后从受保护的网站下载主要证书。
  2. 执行以下两行代码:

    $ openssl x509 -outform der -in GlobalSignRootCA.crt -out GlobalSignRootCA.der
    $ keytool -import -alias GlobalSignRootCA -keystore GlobalSignRootCA.jks -file GlobalSignRootCA.der
  3. 如果在Java SE环境中执行,请添加以下选项:

    $ java -Djavax.net.ssl.trustStore=GlobalSignRootCA.jks -Djavax.net.ssl.trustStorePassword=trustStorePassword -jar MyJar.jar
  4. 或将以下内容添加到Java代码中:

    System.setProperty("javax.net.ssl.trustStore", "GlobalSignRootCA.jks");
    System.setProperty("javax.net.ssl.trustStorePassword","trustStorePassword");

步骤2的另一个选项是仅使用keytool命令。贝娄是带有证书链的示例:

$ keytool -import -file org.eu.crt -alias orgcrt -keystore globalsignrs.jks
$ keytool -import -file GlobalSignOrganizationValidationCA-SHA256-G2.crt -alias globalsignorgvalca -keystore globalsignrs.jks
$ keytool -import -file GlobalSignRootCA.crt -alias globalsignrootca -keystore globalsignrs.jks


3

还有一个GUI工具,允许可视化JKS创建和证书导入。

http://portecle.sourceforge.net/

Portecle是一个用户友好的GUI应用程序,用于创建,管理和检查密钥库,密钥,证书,证书请求,证书吊销列表等。


1
关键商店资源管理器是portecle的现代版本。它们的菜单和功能之间完全没有区别。
Setmax

0

我从互联网上得到的。它对于包含多个条目的pem文件非常有效。

#!/bin/bash
pemToJks()
{
        # number of certs in the PEM file
        pemCerts=$1
        certPass=$2
        newCert=$(basename "$pemCerts")
        newCert="${newCert%%.*}"
        newCert="${newCert}"".JKS"
        ##echo $newCert $pemCerts $certPass
        CERTS=$(grep 'END CERTIFICATE' $pemCerts| wc -l)
        echo $CERTS
        # For every cert in the PEM file, extract it and import into the JKS keystore
        # awk command: step 1, if line is in the desired cert, print the line
        #              step 2, increment counter when last line of cert is found
        for N in $(seq 0 $(($CERTS - 1))); do
          ALIAS="${pemCerts%.*}-$N"
          cat $pemCerts |
                awk "n==$N { print }; /END CERTIFICATE/ { n++ }" |
                $KEYTOOLCMD -noprompt -import -trustcacerts \
                                -alias $ALIAS -keystore $newCert -storepass $certPass
        done
}
pemToJks <pem to import> <pass for new jks>
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.