使用keytool 工具生成keystore檔案,然後通過java 擷取私鑰privatekey 時,報錯:

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)
具體操作如下
使用keystool 生成本地數字證書

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"
運作結果:
說明:keystore的密碼是abcdefg,通過-storepass 指定。
java 代碼如下:

@test
public void test_01() throws exception {
string keystorepath="d:\\temp\\a\\a\\ca\\zlex.keystore";
string password="abcdefg";
// 獲得密鑰庫
keystore ks = getkeystore(keystorepath, password);
// 獲得私鑰
privatekey privatekey = (privatekey) ks.getkey("localhost", password.tochararray());
system.out.println(privatekey);
}
/**
* 獲得keystore
*
* @param keystorepath
* 密鑰庫路徑
* @param password
* 密碼
* @return keystore 密鑰庫
*/
private static keystore getkeystore(string keystorepath, string password)
throws exception {
// 執行個體化密鑰庫
keystore ks = keystore.getinstance(keystore.getdefaulttype());
// 獲得密鑰庫檔案流
fileinputstream is = new fileinputstream(keystorepath);
// 加載密鑰庫
ks.load(is, password.tochararray());
// 關閉密鑰庫檔案流
is.close();
return ks;
運作上述java 代碼時,報錯:java.security.unrecoverablekeyexception: cannot recover key
到底是什麼原因呢?
原因:keystore 密碼和主密碼不同。
解決方法:keystore 密碼和主密碼使用相同的密碼。
(2)tomcat使用keystore檔案啟動報錯
若keystore 密碼和主密碼不同,啟動tomcat時也會報錯
指令:keytool -genkey -alias tomcat -keyalg rsa -keysize 1024 -validity 365 -keystore tomcat22.keystore
生成的檔案 就是:tomcat22.keystore
密碼一和 密碼二必須相同,否則,啟動tomcat 時會報錯。