如何使用javax.net.ssl指定密钥密码?

时间:2013-03-03 03:15:31

标签: java ssl openssl jetty keystore

我遇到了Java SSL的困难。问题是我的密钥有密码。当我使用命令openssl req -new -newkey rsa:1024 -nodes -out local.csr -keyout local.key生成密钥时,当系统询问A challenge password []:时,我输入了MyKeyPass。然后我从证书颁发机构获得了证书。然后我将证书导入KeyStore和TrustStore。

我的一个应用程序基于Jetty并使用Maven运行,另一个使用原始套接字,我没有使用Maven。

当我使用Jetty证书时,使用以下配置,一切正常:

<connector implementation="org.mortbay.jetty.security.SslSelectChannelConnector">
  <port>443</port>
  <maxIdleTime>30000</maxIdleTime>
  <keystore>keys/domain.jks</keystore>
  <password>KeyStorePass</password>
  <keyPassword>MyKeyPass</keyPassword>
  <truststore>keys/truststore_domain.jks</truststore>
  <trustPassword>TrustStorePass</trustPassword>
</connector>

但是,对于不使用Jetty / Maven的应用程序,以下配置无效:

-Djavax.net.ssl.keyStore=./keys/domain.jks \
-Djavax.net.ssl.keyStorePassword=KeyStorePass \
-Djavax.net.ssl.trustStore=./keys/truststore_domain.jks \
-Djavax.net.ssl.trustStorePassword=TrustStorePass \

我收到以下错误:

Caused by: java.security.UnrecoverableKeyException: Cannot recover key
    at sun.security.provider.KeyProtector.recover(KeyProtector.java:328)
    at sun.security.provider.JavaKeyStore.engineGetKey(JavaKeyStore.java:138)
    at sun.security.provider.JavaKeyStore$JKS.engineGetKey(JavaKeyStore.java:55)
    at java.security.KeyStore.getKey(KeyStore.java:792)
    at sun.security.ssl.SunX509KeyManagerImpl.<init>(SunX509KeyManagerImpl.java:131)
    at sun.security.ssl.KeyManagerFactoryImpl$SunX509.engineInit(KeyManagerFactoryImpl.java:68)
    at javax.net.ssl.KeyManagerFactory.init(KeyManagerFactory.java:259)
    at sun.security.ssl.SSLContextImpl$DefaultSSLContext.getDefaultKeyManager(SSLContextImpl.java:621)
    at sun.security.ssl.SSLContextImpl$DefaultSSLContext.<init>(SSLContextImpl.java:486)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
    at java.lang.Class.newInstance0(Class.java:372)
    at java.lang.Class.newInstance(Class.java:325)
    at java.security.Provider$Service.newInstance(Provider.java:1238)
    ... 12 more

当然,它缺少KeyPassword(MyKeyPass)。我一直试图找到如何使用-Djavax.net.ssl语法指定它,但似乎无法找到它。如何指定密钥?

1 个答案:

答案 0 :(得分:6)

您无法通过这些系统属性执行此操作:您必须使用默认设置,使其与密钥库密码保持一致。或者安装自定义KeyManager。