2017-08-03 42 views
1

我想用java apis創建一個來自現有crt文件的密鑰庫「PCKS12」。 有可能嗎?如果是的話,該怎麼做?從crt文件創建p12和keyStore

EDIT

1/ OpenSSL的REQ -newkey RSA:2048 -nodes -keyout keyFile.key -x509 -days 3650 -out certFile.crt
2/ OpenSSL的PKCS12 - 出口-in certFile.crt -inkey keyFile.key退房手續tmp.p12 -name別名
3/ 密鑰工具-importkeystore -srckeystore tmp.p12 -srcstoretype PKCS12 -srcstorepass密碼-destkeystore keySto reFile.jks -deststoretype JKS -deststorepass password -destkeypass password -alias別名

如何以編程方式進行步驟2和3?

+0

假設CRT文件只包含一個公共密鑰,它不會做你多好。一個p12文件通常是一個公鑰/私鑰對。 – rmlan

回答

2

您可以創建一個包含Java的keytool一個根CA PKCS#12密鑰庫:

keytool -importcert -trustcacerts -keystore keystore.p12 -storetype pkcs12 \ 
    -alias root -file root.crt 

系統將提示您爲將要用來保護密鑰存儲的完整性的密碼,這樣就沒有你可以修改你的信任錨而不需要檢測。您可以使用其他選項指定密碼,但可能會在系統上留下密碼記錄。

這裏,-trustcacerts表示您信任您正在導入的證書作爲認證機構。如果不填寫,則會顯示證書,並且系統會提示您檢查並接受它。

別名「root」實際上是商店中證書的暱稱,它可以是任何可以幫助您稍後識別此證書的暱稱。

而且,當然,文件「root.crt」是您要導入的CA證書。


編程方式:

static void createTrustStore(Path certificate, Path keystore, char[] password) 
     throws IOException, GeneralSecurityException { 
    CertificateFactory cf = CertificateFactory.getInstance("X.509"); 
    Certificate root; 
    try (InputStream is = Files.newInputStream(certificate)) { 
     root = cf.generateCertificate(is); 
    } 
    KeyStore pkcs12 = KeyStore.getInstance("PKCS12"); 
    pkcs12.load(null, null); 
    pkcs12.setCertificateEntry("root", root); 
    try (OutputStream os = Files.newOutputStream(keystore, StandardOpenOption.CREATE_NEW)) { 
     pkcs12.store(os, password); 
    } 
} 

private static final byte[] HEADER = "-----".getBytes(StandardCharsets.US_ASCII); 

static void createIdentityStore(Path certificate, Path key, Path keystore, char[] password) 
     throws IOException, GeneralSecurityException { 
    byte[] pkcs8 = decode(Files.readAllBytes(key)); 
    KeyFactory kf = KeyFactory.getInstance("RSA"); 
    PrivateKey pvt = kf.generatePrivate(new PKCS8EncodedKeySpec(pkcs8)); 
    CertificateFactory cf = CertificateFactory.getInstance("X.509"); 
    Certificate pub; 
    try (InputStream is = Files.newInputStream(certificate)) { 
     pub = cf.generateCertificate(is); 
    } 
    KeyStore pkcs12 = KeyStore.getInstance("PKCS12"); 
    pkcs12.load(null, null); 
    pkcs12.setKeyEntry("identity", pvt, password, new Certificate[] { pub }); 
    try (OutputStream s = Files.newOutputStream(keystore, StandardOpenOption.CREATE_NEW)) { 
     pkcs12.store(s, password); 
    } 
} 

private static byte[] decode(byte[] raw) { 
    if (!Arrays.equals(Arrays.copyOfRange(raw, 0, HEADER.length), HEADER)) return raw; 
    CharBuffer pem = StandardCharsets.US_ASCII.decode(ByteBuffer.wrap(raw)); 
    String[] lines = Pattern.compile("\\R").split(pem); 
    String[] body = Arrays.copyOfRange(lines, 1, lines.length - 1); 
    return Base64.getDecoder().decode(String.join("", body)); 
} 
+0

我想以編程方式創建它 –

+1

@MedBesbes精細 – erickson

+0

你能看到我的編輯請因爲作爲輸入我有.crt和.key文件 –