簡體   English   中英

從 PKCS12 創建私鑰對象

[英]Creating PrivateKey Object from PKCS12

我使用以下命令從 PKCS12 文件創建了私鑰:

openssl pkcs12 -in test.p12 -nocerts -out privateKey.pem

我現在如何從這個privateKey.pem文件創建 PrivateKey 對象?

我嘗試使用以下代碼使用 PKCS12 文件本身:

 KeyStore pfx = KeyStore.getInstance("pkcs12");
 pfx.load(new FileInputStream(P12), "123456".toCharArray());
 final Enumeration<String> aliases = pfx.aliases(); //this is empty

pfx.aliases() - 是空的,我使用 keytool 驗證它真的是空的,沒有條目。

keytool -v -list -storetype pkcs12 -keystore test.p12

Keystore type: PKCS12
Keystore provider: SunJSSE

Your keystore contains 0 entries

我的問題是如何使用這樣的代碼創建 PrivateKey:

 public static RSAPrivateKey getPrivateKey(File privateKeyFile) throws IOException {
        byte[] keyBytes = new byte[(int) privateKeyFile.length()];
        FileInputStream fis = new FileInputStream(privateKeyFile);
        fis.read(keyBytes);
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);// it works only with PKCS8
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(spec);
        return privKey;
    }

此代碼的問題僅適用於 PKCS8,PKCS12 我需要這樣的東西。

我知道的唯一方法有點低級,但它有效:

public PrivateKey getPrivateKey(File file) throws IOException, GeneralSecurityException {
    try (FileInputStream fileStream = new FileInputStream(file);
         DataInputStream dataStream = new DataInputStream(fileStream)) {
        byte[] keyBytes = new byte[(int) file.length()];
        dataStream.readFully(keyBytes);
        String temp = new String(keyBytes);
        String header = temp.replace("-----BEGIN PRIVATE KEY-----\n", "");
        header = header.replace("-----END PRIVATE KEY-----", "");
        byte[] decoded = new Base64().decode(header);
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePrivate(spec);
    }
}

此代碼假定所需的密鑰是 RSA 密鑰。

您可以嘗試使用 KeyStore Explorer ( https://keystore-explorer.org/ ),我們使用它來代替 Java Keytool(因為我覺得它很難使用)。

也許這會幫助某人。

以下是從 pkcs12 證書文件生成私鑰的方法。

public PrivateKey getPrivateKey(String pathToPKCS12File) {
    try {
        InputStream stream = new FileInputStream(new File(pathToPKCS12File));
        KeyStore ks = KeyStore.getInstance("PKCS12");
        ks.load(stream, "123456".toCharArray());
        return (PrivateKey) ks.getKey(
            ks.aliases.nextElement(),
            "123456".toCharArray()
        );
    } catch (Exception e) {
        //error
    }
}

暫無
暫無

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

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