views:

1312

answers:

2

Hi all

I try to get Key from KeyStore. I created a keystore by 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

And the following is 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());
      }  
}

}

I run on Java 1.6

But have error:

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)

Please help me. Thank you so much.

+1  A: 

This basically means 2 things,

  1. You had a bad password.
  2. Your keystore is corrupted somehow.

I suspect it's #1. Double check your password. Try if you can list the key in keytool with the same password.

ZZ Coder
+2  A: 

In the ks.getEntry line, you're giving it the store password. Should be the key password instead. Replace the line with this and it will work:

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