代碼如下,僅供參考
/**
* 從PFX檔案中擷取私鑰
*
* @param pfxFilePath 檔案存儲目錄
* @param strPassword PFX密碼
*/
private Key getPrivateKeyFormPfx(String pfxFilePath, String strPassword) {
try (FileInputStream fis = new FileInputStream(pfxFilePath)) {
//密碼處理
char[] nPassword = strPassword.toCharArray();
//加載讀取PFX檔案
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(fis, nPassword);
fis.close();
Enumeration<String> enumerations = ks.aliases();
//從檔案中擷取秘鑰
String keyPFXFile = null;
if (enumerations.hasMoreElements()) {
keyPFXFile = enumerations.nextElement();
}
//擷取公鑰
/*Certificate cert = ks.getCertificate(keyPFXFile);
PublicKey pubkey = cert.getPublicKey();*/
return ks.getKey(keyPFXFile, nPassword);
} catch (Exception e) {
logger.error("讀取pfx檔案異常!", e);
}
return null;
}