在Java中将私钥转换为PKCS#8格式 [英] Convert private key to PKCS#8 format in java

查看:1191
本文介绍了在Java中将私钥转换为PKCS#8格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用MSCAPI提供程序从Windows证书存储中获取证书和私钥,然后我需要将它们存储在Java Keystore对象中,但是我遇到了私钥格式问题,该错误显示: java.security.KeyStoreException: Cannot get key bytes, not PKCS#8 encoded 这是我的代码:

I'm trying to get certificates and private keys from windows certificate store using MSCAPI provider, then i need to store them in a Java Keystore object, but i'm facing a problem of private keys format, the error says: java.security.KeyStoreException: Cannot get key bytes, not PKCS#8 encoded Here's my code:

SunMSCAPI providerMSCAPI = new SunMSCAPI();
Security.addProvider(providerMSCAPI);
KeyStore ks = KeyStore.getInstance("Windows-MY");
ks.load(null, null);
PrivateKey privateKey = null;
X509Certificate cert = null;
cert = (X509Certificate) ks.getCertificate("ALIAS");
if (ks.isKeyEntry("ALIAS")) {
    privateKey = (PrivateKey) ks.getKey("ALIAS", null);
}
KeyStore newKs = null;
...
...
newKs .setKeyEntry("pvKey", privateKey , "pwd".toCharArray(), certifChain);

此外,privateKey.getEncoded()返回null.

推荐答案

将pfx文件以编程方式导入Windows证书存储区,然后尝试稍后再次读取此证书和密钥时,我遇到了完全相同的问题.我相信答案就在于 http://www.oracle.com/technetwork/articles/javase/security-137537.html ,我引述:"...可能不会将由此产生的PKCS#12密钥库导入仅对密钥库及其所有密钥条目使用单个密码的应用程序中".该文档的前面还指出:请注意,SunMSCAPI提供程序产生的密钥是本机句柄的包装对象.因此,它们可能不被其他提供程序接受,并且其行为可能与纯Java提供程序产生的密钥有所不同,例如特别是,不能序列化由SunMSCAPI提供程序生成的RSA私钥".尝试读取私钥时,将导致空算法和空编码数据(如您在上文所述),尽管读取证书的效果很好.另外,您也可以将私钥保存在单独的RSA加密文件中,而不是Windows证书存储区中,或者仅使用原始pfx文件,而不是将pfx导入Windows证书存储区中.

I have exactly the same issue when programatically importing a pfx file into the windows certificate store and then attempting to read this certificate and key again later. I believe the answer lies in http://www.oracle.com/technetwork/articles/javase/security-137537.html and I quote: "...the resulting PKCS#12 keystore may not be imported into applications that use only a single password for the keystore and all its key entries". Earlier in the document it also states: "Note that keys produced by the SunMSCAPI provider are wrapper objects for the native handles. Thus, they may not be accepted by other providers and may behave somewhat differently than keys produced by pure-Java providers, such as SunJCE. In particular, the RSA private keys generated by the SunMSCAPI provider cannot be serialised". Upon trying to read the private key results in null algorithm and null encoded data as you note above, though reading the certificate works fine. Alternatively you could save the PrivateKey in a separate RSA encrypted file instead of the windows certificate store or just work of the original pfx file instead of importing the pfx into the windows certificate store.

这篇关于在Java中将私钥转换为PKCS#8格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆