【问题标题】:how to load private key in windows store using Java KeyStore如何使用 Java KeyStore 在 Windows 商店中加载私钥
【发布时间】:2018-04-16 13:41:01
【问题描述】:

我正在处理这个 Java 项目,我需要使用提供程序 SunMSCAPI 从 Windows KeyStore 加载私钥,但我根本不提供任何密码,我不知道是否需要这样做。 这是我正在做的示例测试用例:

public static void main(String[] args) throws Throwable {
    Provider provider = Security.getProvider("SunMSCAPI");
    KeyStore wins=KeyStore.getInstance("Windows-MY", provider);
    wins.load(null, null);
    Enumeration<String> aliases = wins.aliases();
    while (aliases.hasMoreElements()) {
        String alias = (String) aliases.nextElement();
        System.out.println(alias);
        Certificate[] chain = wins.getCertificateChain(alias);
        X509Certificate[] x509 = CERManager.toX509(chain);
        for (int i = 0; i < x509.length; i++) {
            System.out.println(x509[i].getSubjectX500Principal());
        }
        Key key = wins.getKey(alias, "1234".toCharArray());
        System.out.println(key);

    }

}

当我运行它时,我得到了一些我之前使用 Adob​​e Reader 从 pfx 文件中导入的证书,但我无法获得与该证书对应的私钥,而是得到了 null。

有关此问题的任何帮助?提前谢谢

【问题讨论】:

    标签: java windows keystore mscapi


    【解决方案1】:

    我想我找到了解决我的问题的解决方案。 我尝试使用这段代码在 Java 中导入 pfx

    private static void importPFX(File pfxFile, char pass[]) throws Exception {
        SunMSCAPI providerMSCAPI = new SunMSCAPI();
        Security.addProvider(providerMSCAPI);
        KeyStore wins=KeyStore.getInstance("Windows-MY", providerMSCAPI);
        wins.load(null, null);
        BouncyCastleProvider bcp = new BouncyCastleProvider();
        Security.addProvider(bcp);
        KeyStore pfx = KeyStore.getInstance("PKCS12","BC");
        pfx.load(new FileInputStream(pfxFile), pass);
    
        Enumeration<String> aliases = pfx.aliases();
        while (aliases.hasMoreElements()) {
            String alias = (String) aliases.nextElement();
            Certificate[] chain = pfx.getCertificateChain(alias);
            X509Certificate x509[]=new X509Certificate[chain.length];
            for (int i = 0; i < chain.length; i++) {
                x509[i]=(X509Certificate) chain[i];
            }
            X500Name x500name = new JcaX509CertificateHolder(x509[0]).getSubject();
            RDN cn = x500name.getRDNs(BCStyle.CN)[0];
    
            String commonName = IETFUtils.valueToString(cn.getFirst().getValue());
            PrivateKey pkey = (PrivateKey) pfx.getKey(alias, pass);
            System.out.println(pkey);
            wins.setKeyEntry(commonName, pkey, "1234".toCharArray(), new X509Certificate[]{x509[0]});
            wins.store(null, null);
        }
    }
    

    然后我使用问题中的第一个代码列出了 Windows Key Store 的密钥和证书,我得到了私钥。

    一个重要的细节,当导入证书和私钥时,你应该只传递用户证书,而不是整个链。至少是它对我有用的唯一方法。

    【讨论】:

      猜你喜欢
      • 2020-10-23
      • 2012-04-11
      • 1970-01-01
      • 2021-05-27
      • 1970-01-01
      • 2013-07-15
      • 1970-01-01
      • 1970-01-01
      • 2019-12-07
      相关资源
      最近更新 更多