【问题标题】:Convert java keystore to PFX through java programming通过java编程将java keystore转换为PFX
【发布时间】:2013-03-23 09:06:49
【问题描述】:

我需要支持与 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 我也搜索了这个,但我找不到这个类的任何一般编程帮助。如果有人有任何提示或想法,请分享。

【问题讨论】:

    标签: java keystore keytool pfx


    【解决方案1】:

    我不知道 KeyTool 类,而且由于它不是公共 API,我不愿意使用它,但您可以使用 KeyStore 类自己读写密钥库。根据documentation,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);
        }
    }
    

    【讨论】:

    • 感谢我不知道如何创建 pfx (pkcs12 密钥库),它看起来很简单。我会试试谢谢
    猜你喜欢
    • 2013-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    • 2010-09-29
    • 2020-06-06
    相关资源
    最近更新 更多