在 JVM 中注册多个密钥库
Posted
技术标签:
【中文标题】在 JVM 中注册多个密钥库【英文标题】:Registering multiple keystores in JVM 【发布时间】:2010-12-20 02:55:01 【问题描述】:我有两个应用程序在同一个 java 虚拟机中运行,并且都使用不同的密钥库和信任库。
一个可行的选择是使用单个密钥库并将所有其他密钥库导入共享密钥库(例如 keytool -import),但如果我可以为在同一个 jvm 中运行的不同应用程序使用单独的密钥库,这将真的有助于我的要求.
我可以将密钥库和信任库设置为用作 jvm 参数或系统属性,如下所示:
java -Djavax.net.ssl.keyStore=serverKeys
-Djavax.net.ssl.keyStorePassword=password
-Djavax.net.ssl.trustStore=serverTrust
-Djavax.net.ssl.trustStorePassword=password SSLApplication
或
System.setProperty("javax.net.ssl.keyStore","serverKeys")
但这种方法的问题在于它指定了要在 JVM 级别使用的密钥库/信任库,因此在同一个 JVM 中运行的所有应用程序都会获得相同的密钥库/信任库。
我也尝试过创建自定义 SSLContext 并将其设置为默认值,但它也会为在同一 JVM 中运行的所有应用程序设置上下文。
SSLContext context = SSLContext.getInstance("SSL");
context.init(kms, tms, null);
SSLContext.setDefault(context);
我希望能够在不修改单个应用程序代码的情况下使用不同的密钥库/信任库。
除了 jre 中的默认密钥库/证书之外,还可以动态注册多个密钥库到 jvm 中的解决方案会很棒。
解决方案将以这种方式工作:
当 JVM 启动时,它会加载所有默认证书/密钥库 来自 jre/certs 文件夹(未指定密钥库时的默认 java 行为)。 当应用 1 加载时,它会注册其密钥库, 然后,当 App 2 加载时,它会注册其密钥库...请让我知道您的想法或解决方案。 提前致谢!
【问题讨论】:
如果您认为您的问题与此不同,请澄清:***.com/questions/1788031/… 我已经添加了我的工作代码,它可以用来回答我的问题,由 sylvarking 引用。 感谢 sylvarking 和软件猴子。如果自定义密钥/信任库不起作用,我需要故障转移到 Java 的默认密钥/信任库。我正在处理您提供的代码,我需要对其进行调整,以便它与默认的 JVM 密钥管理器一起使用。 安卓开发者可以参考我的回答here。 【参考方案1】:Raz 的回答是一个很好的开始,但不够灵活,无法满足我的需求。 MultiStoreKeyManager 显式检查自定义 KeyManager,然后在操作失败时回退到 jvm KeyManager。我实际上想先检查 jvm 证书;最好的解决方案应该能够处理任何一种情况。此外,答案无法提供有效的 TrustManager。
我编写了几个更灵活的类,CompositeX509KeyManager 和 CompositeX509TrustManager,它们以任意顺序添加了对任意数量的密钥库的支持。
CompositeX509KeyManager
package com.mycompany.ssl;
import java.net.Socket;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.List;
import javax.annotation.Nullable;
import javax.net.ssl.X509KeyManager;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
/**
* Represents an ordered list of @link X509KeyManagers with most-preferred managers first.
*
* This is necessary because of the fine-print on @link SSLContext#init:
* Only the first instance of a particular key and/or trust manager implementation type in the
* array is used. (For example, only the first javax.net.ssl.X509KeyManager in the array will be used.)
*
* @author codyaray
* @since 4/22/2013
* @see http://***.com/questions/1793979/registering-multiple-keystores-in-jvm
*/
public class CompositeX509KeyManager implements X509KeyManager
private final List keyManagers;
/**
* Creates a new @link CompositeX509KeyManager.
*
* @param keyManagers the X509 key managers, ordered with the most-preferred managers first.
*/
public CompositeX509KeyManager(List keyManagers)
this.keyManagers = ImmutableList.copyOf(keyManagers);
/**
* Chooses the first non-null client alias returned from the delegate
* @link X509TrustManagers, or @code null if there are no matches.
*/
@Override
public @Nullable String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket)
for (X509KeyManager keyManager : keyManagers)
String alias = keyManager.chooseClientAlias(keyType, issuers, socket);
if (alias != null)
return alias;
return null;
/**
* Chooses the first non-null server alias returned from the delegate
* @link X509TrustManagers, or @code null if there are no matches.
*/
@Override
public @Nullable String chooseServerAlias(String keyType, Principal[] issuers, Socket socket)
for (X509KeyManager keyManager : keyManagers)
String alias = keyManager.chooseServerAlias(keyType, issuers, socket);
if (alias != null)
return alias;
return null;
/**
* Returns the first non-null private key associated with the
* given alias, or @code null if the alias can't be found.
*/
@Override
public @Nullable PrivateKey getPrivateKey(String alias)
for (X509KeyManager keyManager : keyManagers)
PrivateKey privateKey = keyManager.getPrivateKey(alias);
if (privateKey != null)
return privateKey;
return null;
/**
* Returns the first non-null certificate chain associated with the
* given alias, or @code null if the alias can't be found.
*/
@Override
public @Nullable X509Certificate[] getCertificateChain(String alias)
for (X509KeyManager keyManager : keyManagers)
X509Certificate[] chain = keyManager.getCertificateChain(alias);
if (chain != null && chain.length > 0)
return chain;
return null;
/**
* Get all matching aliases for authenticating the client side of a
* secure socket, or @code null if there are no matches.
*/
@Override
public @Nullable String[] getClientAliases(String keyType, Principal[] issuers)
ImmutableList.Builder aliases = ImmutableList.builder();
for (X509KeyManager keyManager : keyManagers)
aliases.add(keyManager.getClientAliases(keyType, issuers));
return emptyToNull(Iterables.toArray(aliases.build(), String.class));
/**
* Get all matching aliases for authenticating the server side of a
* secure socket, or @code null if there are no matches.
*/
@Override
public @Nullable String[] getServerAliases(String keyType, Principal[] issuers)
ImmutableList.Builder aliases = ImmutableList.builder();
for (X509KeyManager keyManager : keyManagers)
aliases.add(keyManager.getServerAliases(keyType, issuers));
return emptyToNull(Iterables.toArray(aliases.build(), String.class));
@Nullable
private static <T> T[] emptyToNull(T[] arr)
return (arr.length == 0) ? null : arr;
CompositeX509TrustManager
package com.mycompany.ssl;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;
import javax.net.ssl.X509TrustManager;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
/**
* Represents an ordered list of @link X509TrustManagers with additive trust. If any one of the
* composed managers trusts a certificate chain, then it is trusted by the composite manager.
*
* This is necessary because of the fine-print on @link SSLContext#init:
* Only the first instance of a particular key and/or trust manager implementation type in the
* array is used. (For example, only the first javax.net.ssl.X509KeyManager in the array will be used.)
*
* @author codyaray
* @since 4/22/2013
* @see http://***.com/questions/1793979/registering-multiple-keystores-in-jvm
*/
public class CompositeX509TrustManager implements X509TrustManager
private final List trustManagers;
public CompositeX509TrustManager(List trustManagers)
this.trustManagers = ImmutableList.copyOf(trustManagers);
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException
for (X509TrustManager trustManager : trustManagers)
try
trustManager.checkClientTrusted(chain, authType);
return; // someone trusts them. success!
catch (CertificateException e)
// maybe someone else will trust them
throw new CertificateException("None of the TrustManagers trust this certificate chain");
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException
for (X509TrustManager trustManager : trustManagers)
try
trustManager.checkServerTrusted(chain, authType);
return; // someone trusts them. success!
catch (CertificateException e)
// maybe someone else will trust them
throw new CertificateException("None of the TrustManagers trust this certificate chain");
@Override
public X509Certificate[] getAcceptedIssuers()
ImmutableList.Builder certificates = ImmutableList.builder();
for (X509TrustManager trustManager : trustManagers)
certificates.add(trustManager.getAcceptedIssuers());
return Iterables.toArray(certificates.build(), X509Certificate.class);
用法
对于一个 keystore + jvm keystore 的标准情况,您可以像这样连接它。我再次使用 Guava,但这次是在 Guicey 包装器中:
@Provides @Singleton
SSLContext provideSSLContext(KeyStore keystore, char[] password)
String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
X509KeyManager customKeyManager = getKeyManager("SunX509", keystore, password);
X509KeyManager jvmKeyManager = getKeyManager(defaultAlgorithm, null, null);
X509TrustManager customTrustManager = getTrustManager("SunX509", keystore);
X509TrustManager jvmTrustManager = getTrustManager(defaultAlgorithm, null);
KeyManager[] keyManagers = new CompositeX509KeyManager(ImmutableList.of(jvmKeyManager, customKeyManager)) ;
TrustManager[] trustManagers = new CompositeX509TrustManager(ImmutableList.of(jvmTrustManager, customTrustManager)) ;
SSLContext context = SSLContext.getInstance("SSL");
context.init(keyManagers, trustManagers, null);
return context;
private X509KeyManager getKeyManager(String algorithm, KeyStore keystore, char[] password)
KeyManagerFactory factory = KeyManagerFactory.getInstance(algorithm);
factory.init(keystore, password);
return Iterables.getFirst(Iterables.filter(
Arrays.asList(factory.getKeyManagers()), X509KeyManager.class), null);
private X509TrustManager getTrustManager(String algorithm, KeyStore keystore)
TrustManagerFactory factory = TrustManagerFactory.getInstance(algorithm);
factory.init(keystore);
return Iterables.getFirst(Iterables.filter(
Arrays.asList(factory.getTrustManagers()), X509TrustManager.class), null);
我从my blog post 中提取了这个关于这个问题的内容,它有更多的细节、动机等。所有的代码都在那里,所以它是独立的。 :)
【讨论】:
我对@987654329@ 的工作感到有些惊讶。它将X509Certificate[]
实例添加到列表中,然后将数组列表转换为X509Certificate
s?这是一个更正的(也使用泛型):gist.github.com/JensRantil/9b7fecb3647ecf1e3076
显然,JVM 不附带默认密钥库。见***.com/a/30640992/260805。
使用@Ztyx 作为基础,如果您只想信任系统证书+您的自定义密钥库,我添加了一些便捷方法:gist.github.com/HughJeffner/6eac419b18c6001aeadb
对于我们系统中的某些证书,此解决方案似乎失败了。我作为一个单独的问题问了这个问题。***.com/questions/45166038/…。你能对此发表评论吗?问候
这个答案主要对我有用。但是,当按原样使用它时,由于以下 SSL 调试日志,它不起作用:X509KeyManager passed to SSLContext.init(): need an X509ExtendedKeyManager for SSLEngine use
。结果,我根据您的回答将我的X509KeyManager
更改为X509ExtendedKeyManager
,然后它起作用了!感谢您的回答。【参考方案2】:
在使用了我从 ZZ Coder、sylvarking 和 Software Monkey 收到的代码后,我找到了一个可行的解决方案:
首先,我编写了一个 X509KeyManager,它结合了自定义密钥库和默认密钥库。
class MultiKeyStoreManager implements X509KeyManager
private static final Logger logger = Logger.getLogger(MultiKeyStoreManager.class);
private final X509KeyManager jvmKeyManager;
private final X509KeyManager customKeyManager;
public MultiKeyStoreManager(X509KeyManager jvmKeyManager, X509KeyManager customKeyManager )
this.jvmKeyManager = jvmKeyManager;
this.customKeyManager = customKeyManager;
@Override
public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket)
// try the first key manager
String alias = customKeyManager.chooseClientAlias(keyType, issuers, socket);
if( alias == null )
alias = jvmKeyManager.chooseClientAlias(keyType, issuers, socket);
logger.warn("Reverting to JVM CLIENT alias : " + alias);
return alias;
@Override
public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket)
// try the first key manager
String alias = customKeyManager.chooseServerAlias(keyType, issuers, socket);
if( alias == null )
alias = jvmKeyManager.chooseServerAlias(keyType, issuers, socket);
logger.warn("Reverting to JVM Server alias : " + alias);
return alias;
@Override
public X509Certificate[] getCertificateChain(String alias)
X509Certificate[] chain = customKeyManager.getCertificateChain(alias);
if( chain == null || chain.length == 0)
logger.warn("Reverting to JVM Chain : " + alias);
return jvmKeyManager.getCertificateChain(alias);
else
return chain;
@Override
public String[] getClientAliases(String keyType, Principal[] issuers)
String[] cAliases = customKeyManager.getClientAliases(keyType, issuers);
String[] jAliases = jvmKeyManager.getClientAliases(keyType, issuers);
logger.warn("Supported Client Aliases Custom: " + cAliases.length + " JVM : " + jAliases.length);
return ArrayUtils.join(cAliases,jAliases);
@Override
public PrivateKey getPrivateKey(String alias)
PrivateKey key = customKeyManager.getPrivateKey(alias);
if( key == null )
logger.warn("Reverting to JVM Key : " + alias);
return jvmKeyManager.getPrivateKey(alias);
else
return key;
@Override
public String[] getServerAliases(String keyType, Principal[] issuers)
String[] cAliases = customKeyManager.getServerAliases(keyType, issuers);
String[] jAliases = jvmKeyManager.getServerAliases(keyType, issuers);
logger.warn("Supported Server Aliases Custom: " + cAliases.length + " JVM : " + jAliases.length);
return ArrayUtils.join(cAliases,jAliases);
然后,您可以在创建 SSL 上下文或 SocketFactory 时使用此密钥库管理器。代码需要一些重构和整理,但它运行良好。
/**
* Returns an array of KeyManagers, set up to use the required keyStore.
* This method does the bulk of the work of setting up the custom trust managers.
*
* @param props
*
* @return an array of KeyManagers set up accordingly.
*/
private static KeyManager[] getKeyManagers(Properties props) throws IOException, GeneralSecurityException
// First, get the default KeyManagerFactory.
String alg = KeyManagerFactory.getDefaultAlgorithm();
KeyManagerFactory kmFact = KeyManagerFactory.getInstance(alg);
// Next, set up the KeyStore to use. We need to load the file into
// a KeyStore instance.
FileInputStream fis = new FileInputStream(props.getProperty(SSL_KEYSTORE));
logger.info("Loaded keystore");
KeyStore ks = KeyStore.getInstance("jks");
String keyStorePassword = props.getProperty(SSL_KEYSTORE_PASSWORD);
ks.load(fis, keyStorePassword.toCharArray());
fis.close();
// Now we initialise the KeyManagerFactory with this KeyStore
kmFact.init(ks, keyStorePassword.toCharArray());
// default
KeyManagerFactory dkmFact = KeyManagerFactory.getInstance(alg);
dkmFact.init(null,null);
// Get the first X509KeyManager in the list
X509KeyManager customX509KeyManager = getX509KeyManager(alg, kmFact);
X509KeyManager jvmX509KeyManager = getX509KeyManager(alg, dkmFact);
KeyManager[] km = new MultiKeyStoreManager(jvmX509KeyManager, customX509KeyManager) ;
logger.debug("Number of key managers registered:" + km.length);
return km;
/**
* Find a X509 Key Manager compatible with a particular algorithm
* @param algorithm
* @param kmFact
* @return
* @throws NoSuchAlgorithmException
*/
private static X509KeyManager getX509KeyManager(String algorithm, KeyManagerFactory kmFact)
throws NoSuchAlgorithmException
KeyManager[] keyManagers = kmFact.getKeyManagers();
if (keyManagers == null || keyManagers.length == 0)
throw new NoSuchAlgorithmException("The default algorithm :" + algorithm + " produced no key managers");
X509KeyManager x509KeyManager = null;
for (int i = 0; i < keyManagers.length; i++)
if (keyManagers[i] instanceof X509KeyManager)
x509KeyManager = (X509KeyManager) keyManagers[i];
break;
if (x509KeyManager == null)
throw new NoSuchAlgorithmException("The default algorithm :"+ algorithm + " did not produce a X509 Key manager");
return x509KeyManager;
private static void initialiseManager(Properties props) throws IOException, GeneralSecurityException
// Next construct and initialise a SSLContext with the KeyStore and
// the TrustStore. We use the default SecureRandom.
SSLContext context = SSLContext.getInstance("SSL");
context.init(getKeyManagers(props), getTrustManagers(props), null);
SSLContext.setDefault(context);
如果有人有任何问题或需要任何演示代码,请告诉我。
【讨论】:
我还必须添加 MultiKeyStoreTrustManager 以及 getX509TrustManager() 和 getTrustManagers(..) 函数。它们或多或少地直接并行给定的 KeyManager 代码,但没有它就无法工作。【参考方案3】:也许我迟到了 10 年才回答这个问题,但它也可能对其他开发人员有所帮助。我也遇到了加载多个密钥库作为密钥材料/信任材料的相同挑战。我发现了这个页面和 Cody A. Ray 提供的答案。在对多个项目使用相同的 sn-p 之后,我认为创建一个库并将其公开以回馈社区会很方便。请看这里:Github - SSLContext-Kickstart 包含 Cody A. Ray 的 CompositeKeyManager 和 CompositeTrustManager 的代码 sn-p。
用法:
import nl.altindag.ssl.SSLFactory;
import javax.net.ssl.SSLContext;
public class App
public static void main(String[] args)
String keyStorePathOne = ...;
String keyStorePathTwo = ...;
String trustStorePathOne = ...;
String trustStorePathTwo = ...;
char[] password = "password".toCharArray();
SSLFactory sslFactory = SSLFactory.builder()
.withIdentityMaterial(keyStorePathOne, password)
.withIdentityMaterial(keyStorePathTwo, password)
.withTrustMaterial(trustStorePathOne, password)
.withTrustMaterial(trustStorePathTwo, password)
.build();
SSLContext sslContext = sslFactory.getSslContext();
我不太确定是否应该在此处发布此内容,因为它也可以被视为宣传“我的图书馆”的一种方式,但我认为它可能对开发人员有所帮助。
【讨论】:
nl.altindag.ssl.exception.GenericKeyStoreException: KeyStore 不存在给输入 嗨@ЛеонидДубравский 代码示例使用该方法从类路径加载给定输入的密钥库。它会抛出运行时异常,因为它在类路径中找不到它,您能否验证它是否实际存在于类路径中以及给定路径是否正确? 仓库应该在项目目录下?我不能指定路径? :SSLFactory sslFactory = SSLFactory.builder() .withIdentityMaterial("/home/efficeon/cert.jks", keyPass.toCharArray(), "JKS") 是的,你真的可以!当不是来自类路径时,库需要不同类型的输入。它使用 Java 非阻塞输入输出又名 NIO api。您可以使用以下代码 sn-p 重试并在此处分享您的结果:SSLFactory.builder() .withIdentityMaterial(Paths.get("/home/efficeon/cert.jks"), keyPass.toCharArray(), "JKS").build()
Paths.get() 帮助了我,谢谢。但是我使用的是 SNIMatcher matcher = SNIHostName.createSNIMatcher ("local-print. (work | ua)") 并且在访问 local-print.work 或 local-print.ua 时,浏览器仅从第一个商店获取第一个证书。 【参考方案4】:
看看我对这个问题的回答,
How can I have multiple SSL certificates for a Java server
如果您使用 MyKeyManager,您可以拥有多个密钥库,也可以将一个密钥库用于多个上下文。
【讨论】:
感谢您的回答。如果自定义密钥/信任库不起作用,我需要故障转移到 Java 的默认密钥/信任库。我正在处理您提供的代码,我需要对其进行调整,以便它与默认的 JVM 密钥管理器一起使用。以上是关于在 JVM 中注册多个密钥库的主要内容,如果未能解决你的问题,请参考以下文章
用户配置文件和 HKLM 注册表均不可用。使用临时密钥存储库。应用程序退出时,受保护的数据将不可用