如何使用 Java KeyStore 在 Windows Store 中加载私钥



我正在做这个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);
    }
}

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

围绕此问题有任何帮助吗? 提前感谢

我想

我找到了解决我问题的解决方案。我尝试使用这段代码在 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 密钥存储的密钥和证书,我得到了私钥 OK。

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

最新更新