我尝试从KeyStore获取Key。 我用Keytool创建了一个密钥库:
keytool -genkeypair -dname“cn = Mark Jones,ou = JavaSoft,o = Sun,c = US”-alias business2 -keypass abcdtest -keystore C:\ workspace \ XMLSample \ keystore \ mykeystore.jks -storepass 123456 < / p>
以下是GenerateXML.java
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
import javax.xml.crypto.dsig.XMLSignContext;
import javax.xml.crypto.dsig.XMLSignatureFactory;
import javax.xml.crypto.dsig.dom.DOMSignContext;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
public class GenerateXML {
public static void main(String[] args) throws Exception {
try {
char[] passwd = "123456".toCharArray();
//Load the KeyStore and get the signing key and certificate
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream("C:\\workspace\\XMLSample\\keystore\\mykeystore.jks"), passwd);
KeyStore.PrivateKeyEntry keyEnt = (KeyStore.PrivateKeyEntry)ks.getEntry("business2", new KeyStore.PasswordProtection(passwd)); // -> ERROR IN THIS ROW
X509Certificate cert = (X509Certificate)keyEnt.getCertificate();
//Create a DOMSignContext
XMLSignContext context = new DOMSignContext(keyEnt.getPrivateKey(), doc.getDocumentElement()) ;
//Create a DOM XMLSignatureFactory
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
} catch(Exception e) {
e.printStackTrace();
throw new Exception(e.toString());
}
}
}
我在Java 1.6上运行
但有错误:
java.security.UnrecoverableKeyException: Cannot recover key
at sun.security.provider.KeyProtector.recover(KeyProtector.java:311)
at sun.security.provider.JavaKeyStore.engineGetKey(JavaKeyStore.java:121)
at sun.security.provider.JavaKeyStore$JKS.engineGetKey(JavaKeyStore.java:38)
at java.security.KeyStoreSpi.engineGetEntry(KeyStoreSpi.java:456)
at java.security.KeyStore.getEntry(KeyStore.java:1261)
at xml.generate.GenerateXML.main(GenerateXML.java:31)
答案 0 :(得分:24)
我遇到了类似的问题。问题的根源是我使用了与密钥不同的密钥而不是整个密钥库。 代码类似于JSSE文章中的代码。它看起来像这样:
serverKeyStore.load(new FileInputStream("resource/server.jks"), passphrase.toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(serverKeyStore);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(serverKeyStore, keyphrase.toCharArray());
我在第一行使用密钥库传递,在最后一行使用密钥传递。
答案 1 :(得分:19)
这基本上意味着两件事,
我怀疑它是#1。仔细检查您的密码。尝试使用相同的密码列出keytool中的密钥。
答案 2 :(得分:9)
在ks.getEntry行中,您将为其提供商店密码。应该是密钥密码。用这个替换该行,它将起作用:
char[] keypwd = "abcdtest".toCharArray();
KeyStore.PrivateKeyEntry keyEnt = (KeyStore.PrivateKeyEntry) ks.getEntry("business2", new KeyStore.PasswordProtection(keypwd));