无法从密钥库获取密钥


问题内容

我尝试从KeyStore获取密钥。我通过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

以下是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)

问题答案:

这基本上意味着两件事,

  1. 您的密码错误。
  2. 您的密钥库已损坏。

我怀疑是第一名。仔细检查您的密码。尝试是否可以使用相同的密码在keytool中列出密钥。