[英]How to add a private key to Windows Cert Store programmatically
I extracted a Key and its certification chain from a JKS, and now I'm trying to add this key to the Windows Keystore using Java.我从 JKS 中提取了一个密钥及其认证链,现在我正在尝试使用 Java 将此密钥添加到 Windows 密钥库。
To load my JKS I did the following:要加载我的 JKS,我执行了以下操作:
String jksPath = "D:\\mykeystore.jks";
KeyStore keystore = KeyStore.getInstance("JKS");
FileInputStream fIn = new FileInputStream(jksPath);
keystore.load(fIn, "12345678".toCharArray());
Then I get the key and the certification chain:然后我得到了密钥和认证链:
Key key = keystore.getKey("res1", "12345678".toCharArray());
Certificate[] cchain = keystore.getCertificateChain("res1");
So far so good, then I try to add this key to my Windows Keystore:到目前为止一切顺利,然后我尝试将此密钥添加到我的 Windows 密钥库:
KeyStore ks = KeyStore.getInstance("Windows-MY");
ks.load(null, null);
ks.setKeyEntry("myKey", key, "12345678".toCharArray(), cchain);
And BOOM :和繁荣:
Exception in thread "main" java.lang.ClassCastException: [Ljava.security.cert.Certificate;
线程“main”中的异常 java.lang.ClassCastException: [Ljava.security.cert.Certificate; cannot be cast to [Ljava.security.cert.X509Certificate;
不能转换为 [Ljava.security.cert.X509Certificate; at sun.security.mscapi.KeyStore.engineSetKeyEntry(KeyStore.java:402) at sun.security.mscapi.KeyStore$MY.engineSetKeyEntry(KeyStore.java:62) at java.security.KeyStore.setKeyEntry(KeyStore.java:909)
在 sun.security.mscapi.KeyStore.engineSetKeyEntry(KeyStore.java:402) 在 sun.security.mscapi.KeyStore$MY.engineSetKeyEntry(KeyStore.java:62) 在 java.security.KeyStore.setKeyEntry(KeyStore.java:909) )
Exception thrown due to the setKeyEntry call.由于setKeyEntry调用而引发的异常。
PS: when I use the same syntaxe on a JKS type of Keystore no exception is thrown. PS:当我在 JKS 类型的 Keystore 上使用相同的语法时,不会引发异常。
It seems there's a clumsy bit of java code in the implementation of sun.security.mscapi.KeyStore.engineSetKeyEntry().在 sun.security.mscapi.KeyStore.engineSetKeyEntry() 的实现中似乎有一些笨拙的 java 代码。 It tries to convert an array of Certificates ("[Ljava.security.cert.Certificate", notice the prefix in the class name) to an array of X509Certificates (" [Ljava.security.cert.X509Certificate"), which is not something java ever allows you to do with a simple cast expression (eg see discussion of a similar mistake).
它尝试将证书数组(“[Ljava.security.cert.Certificate”,注意类名中的前缀)转换为 X509Certificates数组(“[Ljava.security.cert.X509Certificate”),这不是什么东西java 曾经允许您使用简单的强制转换表达式(例如,参见对类似错误的讨论)。
All I did in a similar situation is to pass the certificate array to the keyStore.setKeyEntry() method call as a X509Certificate array, rather than a simple Certificate array.我在类似情况下所做的只是将证书数组作为 X509Certificate 数组而不是简单的证书数组传递给 keyStore.setKeyEntry() 方法调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.