(1) Java code gets the private key through keystore file and reports an error
When using keytool to generate keystore file and then obtain private key through Java, an error is reported
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.KeyStore.getKey(KeyStore.java:763)
at com.jn.test.TestCA.test_01(TestCA.java:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
The specific operation is as follows
Using keystone to generate local digital certificate
keytool -genkeypair -keyalg RSA -keysize 2048 -sigalg SHA1withRSA -validity 36000 -alias localhost -storepass abcdefg -keystore zlex.keystore -dname "CN=localhost, OU=zlex,O=zlex, L=BJ, ST=BJ, C=CN"
Results of operation:
Note: the password of keystore is ABCDEFG, which is specified by – storepass
The Java code is as follows:
@Test
public void test_01() throws Exception {
String keyStorePath="d:\\Temp\\a\\a\\ca\\zlex.keystore";
String password="abcdefg";
// Get the key store
KeyStore ks = getKeyStore(keyStorePath, password);
// Get the private key
PrivateKey privateKey = (PrivateKey) ks.getKey("localhost", password.toCharArray());
System.out.println(privateKey);
}
/**
* Get KeyStore
*
* @param keyStorePath
* KeyStorePath
* @param password
* password
* @return KeyStore keystore
*/
private static KeyStore getKeyStore(String keyStorePath, String password)
throws Exception {
// Instantiate the keystore
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
// Get the keystore file stream
FileInputStream is = new FileInputStream(keyStorePath);
// load the keystore
ks.load(is, password.toCharArray());
// Close the keystore file stream
is.close();
return ks;
}
When running the above java code, an error is reported: java. Security. Unrecoverable keyexception: cannot recover key 0
What is the reason
Reason: the keystore password is different from the master password
Solution: keystore password and master password use the same password
Please refer to: http://stackoverflow.com/questions/4926290/java-keystore-and-password-settings
(2) Tomcat uses keystore file to start error reporting
If the keystore password is different from the master password, an error will be reported when starting Tomcat
Command: keytool – genkey – alias Tomcat – keyalg RSA – keysize 1024 – validity 365 – keystoretomcat22.keystore
The generated file is tomcat22.keystore
Password 1 and password 2 must be the same, otherwise, an error will be reported when starting Tomcat