关于java:无法从KeyStore获取密钥

Can not get key from KeyStore

我试图从密钥库中获取密钥。我用keytool创建了一个keystore:

keytool-genkeypair-dname"cn=mark jones,ou=javasoft,o=sun,c=us"-alias business2-keypass abcdest-keystore c:workspacexmlsamplekeystoremykeystore.jks-storepass 123456

下面是generatexml.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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上运行

但有错误:

1
2
3
4
5
6
7
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)


我遇到了类似的问题。问题的根源在于,我对密钥使用的密码与对整个密钥库使用的密码不同。代码与JSSE文章中的代码类似。看起来是这样的:

1
2
3
4
5
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。再次检查您的密码。如果可以用相同的密码列出keytool中的密钥,请尝试。


    在ks.getentry行中,您给它存储密码。应该是密钥密码。用此替换行,它将工作:

    1
    2
    char[] keypwd ="abcdtest".toCharArray();
    KeyStore.PrivateKeyEntry keyEnt = (KeyStore.PrivateKeyEntry) ks.getEntry("business2", new KeyStore.PasswordProtection(keypwd));