簡體   English   中英

通過java編程將java密鑰庫轉換為PFX

[英]Convert java keystore to PFX through java programming

我需要支持Keytool.exe的相同功能,通過使用KeyTool類通過編程將java密鑰庫轉換為PFX文件。 由於項目要求的限制,我無法從我的應用程序中使用命令提示進程,因此通過編程我也無法打開命令進程。

例如

C:\\ keytool -importkeystore -srckeystore .k eystore -srcstoretype JKS -destkeystore thekeystore.pfx -deststoretype PKCS12

我可以使用上面的命令通過keytool.exe創建PFX文件,但我的要求是通過我自己的應用程序中的密鑰庫生成PFX文件。 我在谷歌搜索了很多,我找不到任何有用的鏈接,可以提供任何有關此問題的參考或幫助。 有一個類sun.security.tools.Keytool我搜索了這個,但我無法找到任何一般編程幫助這個類。 如果有人有任何提示或想法,請分享。

我不知道KeyTool類,因為它不是公共API,我不願意使用它,但你可以使用KeyStore類自己讀寫密鑰庫。 根據文檔 ,Java至少支持jkspkcs12密鑰庫類型,因此您可以執行以下操作:

public void convertKeystore(Path sourceKeystorePath,
                            char[] sourceKeystorePassword,
                            Path destKeystorePath,
                            char[] destKeystorePassword)
throws GeneralSecurityException, IOException {

    KeyStore sourceKeystore = KeyStore.getInstance("jks");
    try (InputStream stream =
            new BufferedInputStream(
                Files.newInputStream(sourceKeystorePath))) {
        sourceKeystore.load(stream, sourceKeystorePassword);
    }

    KeyStore destKeystore = KeyStore.getInstance("pkcs12");
    destKeystore.load(null, destKeystorePassword);

    // Assume each alias in a keystore has the same password
    // as the keystore itself.
    KeyStore.ProtectionParameter sourceAliasPassword =
        new KeyStore.PasswordProtection(sourceKeystorePassword);
    KeyStore.ProtectionParameter destAliasPassword =
        new KeyStore.PasswordProtection(destKeystorePassword);

    Enumeration<String> aliasList = sourceKeystore.aliases();
    while (aliasList.hasMoreElements()) {
        String alias = aliasList.nextElement();
        KeyStore.Entry entry =
            sourceKeystore.getEntry(alias, sourceAliasPassword);
        destKeystore.setEntry(alias, entry, destAliasPassword);
    }

    try (OutputStream stream =
            new BufferedOutputStream(
                Files.newOutputStream(destKeystorePath))) {
        destKeystore.store(stream, destKeystorePassword);
    }
}

暫無
暫無

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

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