[英]How to programmatically import a pkcs12 file to a Java keystore
我有 pkcs12 文件(keypair.p12)。 使用 keytool 我可以使用 Java 密鑰庫導入(合並)它:
keytool -importkeystore \
-deststorepass [changeit] -destkeypass [changeit] -destkeystore server.keystore \
-srckeystore server.p12 -srcstoretype PKCS12 -srcstorepass some-password \
-alias [some-alias]
如何以編程方式做同樣的事情?
您可以在此處查找源代碼,因為它是開源的。 有一種方法可以告訴您需要做什么:
private void doImportKeyStore() throws Exception {
if (alias != null) {
doImportKeyStoreSingle(loadSourceKeyStore(), alias);
} else {
if (dest != null || srckeyPass != null) {
throw new Exception(rb.getString(
"if.alias.not.specified.destalias.and.srckeypass.must.not.be.specified"));
}
doImportKeyStoreAll(loadSourceKeyStore());
}
/*
* Information display rule of -importkeystore
* 1. inside single, shows failure
* 2. inside all, shows sucess
* 3. inside all where there is a failure, prompt for continue
* 4. at the final of all, shows summary
*/
}
導入 a.p12 證書文件的關鍵是它已經是一個“密鑰庫”。 這意味着它可以作為“pkcs12”密鑰庫加載,然后復制到另一個“jks”密鑰庫。
public void importP12Certificate(String filePathP12, String passwordP12, String filePathJks, String passwordJKS) throws Exception {
KeyStore p12Store = loadKeystore(filePathP12, passwordP12, "pkcs12");
KeyStore jksStore = loadKeystore(filePathJks, passwordJKS, "jks");
Enumeration aliases = p12Store.aliases();
while (aliases.hasMoreElements()) {
String alias = (String)aliases.nextElement();
if (p12Store.isKeyEntry(alias)) {
System.out.println("Adding key for alias " + alias);
Key key = p12Store.getKey(alias, passwordP12.toCharArray());
Certificate[] chain = p12Store.getCertificateChain(alias);
jksStore.setKeyEntry(alias, key, passwordJKS.toCharArray(), chain);
}
}
storeKeystore(jksStore,filePathJks,passwordJKS);
}
private KeyStore loadKeystore(String keyStoreFile, String keystorePassword, String keystoreType) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException {
File file = new File(keyStoreFile);
InputStream inputStream = new FileInputStream(file);
KeyStore keystore = null;
if(keystore == null){
keystore = KeyStore.getInstance(KeyStore.getDefaultType());
}else{
keystore = KeyStore.getInstance(keystoreType);
}
keystore.load(inputStream, keystorePassword.toCharArray());
return keystore;
}
private void storeKeystore(KeyStore keystore, String keyStoreFile, String keystorePassword) throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException {
File file = new File(keyStoreFile);
FileOutputStream out = new FileOutputStream(file);
keystore.store(out, keystorePassword.toCharArray());
out.close();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.