簡體   English   中英

如何從 PKCS12 文件為 Java 創建密鑰庫和信任庫?

[英]How to create keystore and truststore for Java from a PKCS12 file?

我想使用 Java 調用需要相互 SSL 身份驗證的 Web 服務。

此 web 服務可通過安全且經過身份驗證的連接在服務器端和客戶端進行訪問。

我提供了一個 PKCS12 文件 (.p12) 來建立經過身份驗證的連接,該文件包含 4 個條目:

  • TEST _ CAIH 時間戳(RSA 私鑰)。
  • TEST _ CAIH 時間戳(驗證人:XX - Easy CA)。
  • XX - 簡易 CA(驗證人:XX - 根 CA)。
  • XX - 根 CA(驗證人:XX - 根 CA)。

我需要從 p12 文件創建密鑰庫和信任庫還是不需要它,如何從 p12 文件創建它? 我應該在密鑰庫和/或信任庫中添加哪些密鑰?

先感謝您。

我是否需要從 p12 文件創建密鑰庫和信任庫

它是由你決定。 p12/pfx 是與語言無關的密鑰庫,而 JKS 是 Java 密鑰庫。 您可以使用以下代碼。

我應該在密鑰庫和/或信任庫中添加哪些密鑰?

信任庫不需要密鑰,它只存儲 CA 的受信任證書。 Keystore (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);
    }
    }

如果您需要有關代碼的幫助,請告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM