簡體   English   中英

如何將Base64編碼的pkcs12內容轉換為java.security.PrivateKey?

[英]How to convert Base64 encoded pkcs12 content to java.security.PrivateKey?

我正在通過服務帳戶使用Google Directory API,並且在創建服務帳戶時收到了pkcs12密鑰。

Google確實支持兩種不同的使用方式,即使用密鑰作為java.io.Filejava.security.PrivateKey ,對於PoC,我使用的第一種方式是使用java.io.File創建GoogleCredential對象,

        GoogleCredential credential = new GoogleCredential.Builder()
                .setTransport(httpTransport)
                .setJsonFactory(jsonFactory)
                .setServiceAccountId(serviceAccountId)
                .setServiceAccountScopes(Arrays.asList(DirectoryScopes.ADMIN_DIRECTORY_USER))
                .setServiceAccountUser(serviceAccountUser)
                .setServiceAccountPrivateKeyFromP12File(serviceAccountPrivateKeyFile)
                .build();

它按預期工作,但在我的實際用例中,我不能依賴文件系統,因此無法使用第一種方法。 所以我想用第二種方法來實現實際用例,即使用java.security.PrivateKey ,完成后看起來像下面的樣子。

    GoogleCredential credential = new GoogleCredential.Builder()
            .setTransport(httpTransport)
            .setJsonFactory(jsonFactory)
            .setServiceAccountId(serviceAccountId)
            .setServiceAccountScopes(Arrays.asList(DirectoryScopes.ADMIN_DIRECTORY_USER))
            .setServiceAccountUser(serviceAccountUser)
            .setServiceAccountPrivateKey(serviceAccountPrivateKey)
            .build();

在我的用例中,我需要上載私鑰並將其以base64編碼存儲在數據庫中。 現在,我需要傳遞pkcs12鍵的內容並創建Googlecredential對象。 我想第二種選擇是最合適的方法,但是找不到任何示例來從上傳密鑰的base64編碼內容創建java.security.PrivateKey。

是否可以從pkcs12密鑰的base64編碼內容創建java.security.PrivateKey對象?

還是有其他方法可以實現我的用例?

提前致謝

DarRay

java.securty.KeyStore將任何InputStream用作load()方法,因此您可以使用獲取.p12字節的任何方法來創建它。 這是我使用的另一種方法。 盡管這仍然使用.p12字節的文件,但是您可以引入ByteArrayInputStream或任何InputStream子類:

    private PrivateKey getPrivateKeyFromP12() {
        // Google p12 files all have "notasecret" as the pass and "privatekey" as the PK name
        String p12p = "notasecret";    // not cool!  Change this before exporting your .p12
        try {
            KeyStore keystore = KeyStore.getInstance("PKCS12");
            // This is where you'd adjust to bring in your .p12 bytes or chars
            // as an input stream.  Passwords are a char array!
            keystore.load(
                this.getClass().getClassLoader()
                        .getResourceAsStream("the.p12"),
                p12p.toCharArray());
            // This key name is fixed by Google, but could be changed
            PrivateKey key = (PrivateKey) keystore.getKey("privatekey",
                p12p.toCharArray());
            return key;
        } catch (Exception e) {
            LOG.error("Exception while trying to obtain private key",e);
            return null;
        } 

    }

暫無
暫無

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

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