您可以創建一個包含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));
}
假設CRT文件只包含一個公共密鑰,它不會做你多好。一個p12文件通常是一個公鑰/私鑰對。 – rmlan