具有多个密钥(不同密码)的 JKS

JKS with multiple keys (different passwords)

我有一个 JKS,其中包含使用 keytool 生成的 2 个密钥。 2 个密钥有不同的密码,JKS 密码也与这 2 个密码不同。

如果密钥库中只有一个密钥,它会按预期工作。但是添加另一个密码不同的结果会导致 UnrecoverableKeyException。如果两个密钥具有相同的密码,它仍然可以正常工作。

查看一些与此相关的问题:Java keystore with multiple keys and different passwords, Caused by: java.security.UnrecoverableKeyException: Cannot recover key 看来解决方案是使用相同的密码。但这意味着能够为不同的密钥设置不同的密码是没有意义的;我们可以为整个密钥库设置一个密码并保留它。

查看Tomcat,它似乎也遵循这种对存储和密钥使用相同密码的方法。

这是JDK的限制吗?有没有办法让不同的密钥使用不同的密码?

这不是 JDK 的限制,JSSE Reference Guide 回答了你的问题:

For many factories, such as the default SunX509 KeyManagerFactory from the SunJSSE provider, the KeyStore and password are the only information required to initialize the KeyManagerFactory and thus the first init method is the appropriate one to call. The KeyManagerFactory will query the KeyStore for information about which private key and matching public key certificates should be used for authenticating to a remote socket peer. The password parameter specifies the password that will be used with the methods for accessing keys from the KeyStore. All keys in the KeyStore must be protected by the same password.

Sometimes initialization parameters other than a KeyStore and password are needed by a provider. Users of that provider are expected to pass an implementation of the appropriate ManagerFactoryParameters as defined by the provider. The provider can then call the specified methods in the ManagerFactoryParameters implementation to obtain the needed information.

您现在知道该怎么做了,实施您自己的 ManagerFactoryParameters。但是,如果您还必须更改 Tomcat 的代码,那就是另一回事了。