如何从PKCS12文件为Java创建密钥库和信任库?

时间:2019-11-18 13:48:51

标签: java openssl keystore truststore pkcs#12

我想使用需要相互SSL身份验证的Java调用Web服务。

可以通过服务器端和客户端上的安全且经过身份验证的连接访问此Web服务。

我提供了一个PKCS12文件(.p12)以建立经过身份验证的连接,该文件包含4个条目:

  • 测试_ CAIH时间戳(私有RSA密钥)。
  • 测试_ CAIH时间戳(验证人:XX-Easy CA)。
  • XX-Easy CA(验证方:XX-根 CA)。
  • XX-根CA(验证者:XX-根CA)。

我是否需要从p12文件创建密钥库和信任库,或者不需要,如何从p12文件创建密钥库和信任库? 我应该在密钥库和/或信任库中添加哪些密钥?

谢谢。

1 个答案:

答案 0 :(得分:0)

  

我是否需要从p12文件创建密钥库和信任库

由您决定。 p12 / pfx是与语言无关的密钥库,而JKS是Java密钥库。您可以使用以下代码。

  

我应该在密钥库和/或信任库中添加哪些密钥?

信任存储区不需要密钥,它仅存储CA的受信任证书。 密钥库(JKS / p12 / pfx)包含证书和相应的私钥。它可以用于针对Web服务进行身份验证。

尝试加载p12密钥库并将其导出到Java密钥库。

KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(new FileInputStream(<location of keystore>),"password".toCharArray()); 
FileOutputStream fos = null;
try {
fos = new FileOutputStream(PATH + "newKeyStore.jks");
char[] password = PASSWORD_.toCharArray();
ks.store(fos, password);
} finally {
if (fos != null) {
fos.close();
}
}

如果您具有客户端身份验证证书(cer / p7b)和相应的私钥,则可以使用以下代码。

public static void loadKeyStore(){
        char[] password = "changeit".toCharArray();
        java.security.cert.Certificate[] certArr;
        File file = new File(<location of your cer/p7b here>);
        try {
            byte[] buffer = new byte[(int) file.length()];
            DataInputStream in = new DataInputStream(new FileInputStream(file));
            in.readFully(buffer);
            in.close();
            try (ByteArrayInputStream bais = new ByteArrayInputStream(buffer);) {
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                Collection<?> c = cf.generateCertificates(bais);
                List<Certificate> certList = new ArrayList<Certificate>();
                if (c.isEmpty()) {
                    // If there are no certificates found, the p7b file is probably not in binary format.
                    // It may be in base64 format.
                    // The generateCertificates method only understands raw data.
                } else {
                    Iterator<?> i = c.iterator();
                    while (i.hasNext()) {
                        certList.add((Certificate) i.next());
                    }
                }
                certArr = new java.security.cert.Certificate[certList.size()];
                int i = 0;
                while(i < certList.size()){
                    certArr[i] = certList.get(i);
                    i++;
                }
            }
            PrivateKey key = (PrivateKey) getKeyFromFile(<location of private key here>);
            File f = new File("keystore.jks");
            KeyStore keyStore = KeyStore.getInstance("JKS");
            keyStore.load(null, null);
            keyStore.setKeyEntry(<alias>, key, password, certArr);
            FileOutputStream fos = new FileOutputStream(f);
            keyStore.store(fos, password);
            fos.close();
        }catch (Exception e){
            System.out.println("Exception "+ e);
        }
    }

    public static Key getKeyFromFile(String fileName) throws Exception{
        Key pk = null;
        File f = new File(fileName);
        FileInputStream fis = new FileInputStream(f);
        DataInputStream dis = new DataInputStream(fis);
        byte[] keyBytes = new byte[(int)f.length()];
        dis.readFully(keyBytes);
        dis.close();
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        pk = kf.generatePrivate(spec);
        return pk;
    }

要加载信任库,

public static void loadTrustStore() {
        java.security.cert.Certificate[] certArr;
        java.security.cert.Certificate[] certArr2;
        char[] password = "changeit".toCharArray();
        File file = new File(<root ca location>);
        File file2 = new File(<intermediate ca location>);
        try {
            byte[] buffer = new byte[(int) file.length()];
            DataInputStream in = new DataInputStream(new FileInputStream(file));
            in.readFully(buffer);
            in.close();

            byte[] buffer2 = new byte[(int) file2.length()];
            DataInputStream in2 = new DataInputStream(new FileInputStream(file2));
            in2.readFully(buffer2);
            in2.close();

            try (ByteArrayInputStream bais = new ByteArrayInputStream(buffer);ByteArrayInputStream bais2 = new ByteArrayInputStream(buffer2);) {
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                Collection<?> c = cf.generateCertificates(bais);

                CertificateFactory cf2 = CertificateFactory.getInstance("X.509");
                Collection<?> c2 = cf2.generateCertificates(bais2);

                List<Certificate> certList = new ArrayList<Certificate>();
                List<Certificate> certList2 = new ArrayList<Certificate>();

                if (c.isEmpty()) {
                    // If there are now certificates found, the p7b file is probably not in binary format.
                    // It may be in base64 format.
                    // The generateCertificates method only understands raw data.
                } else {

                    Iterator<?> i = c.iterator();

                    while (i.hasNext()) {
                        certList.add((Certificate) i.next());
                    }
                }

                if (c2.isEmpty()) {
                    // If there are no certificates found, the p7b file is probably not in binary format.
                    // It may be in base64 format.
                    // The generateCertificates method only understands raw data.
                } else {

                    Iterator<?> i = c2.iterator();

                    while (i.hasNext()) {
                        certList2.add((Certificate) i.next());
                    }
                }

                certArr = new java.security.cert.Certificate[certList.size()];
                int i = 0;
                while (i < certList.size()) {
                    certArr[i] = certList.get(i);
                    i++;
                }
                certArr2 = new java.security.cert.Certificate[certList2.size()];
                int j = 0;
                while (j < certList2.size()) {
                    certArr2[j] = certList2.get(j);
                    j++;
                }
            }
            File output = new File("truststore.keystore");
            KeyStore ks = KeyStore.getInstance("PKCS12");
            ks.load(null, null);
            ks.setCertificateEntry(<alias for root ca>, certArr[0]);
            ks.setCertificateEntry(<alias for intermediate ca>, certArr2[0]);
            FileOutputStream fs = new FileOutputStream(output);
            ks.store(fs, password);
            fs.close();
        }catch (Exception e){
        System.out.println("Exception "+ e);
    }
    }

如果您需要代码方面的帮助,请告诉我。