问题描述
关于如何仅使用.key(点密钥)文件和.crt(点crt)文件构建Netty io.netty.handler.ssl.SslContext,我有一个疑问。
强调一下,我正在寻求帮助来构建io.netty.handler.ssl.SslContext,而不是org.apache.http.ssl.SSLContexts。
此外,我正在寻求构建io.netty.handler.ssl.SslContext的帮助,而没有现成的密钥库和信任库。 (将无法直接执行此操作)
public SslContext getSslContext() {
try {
final Path keystorePath = Paths.get(keyStorePath);
final KeyStore keyStore = KeyStore.getInstance(keyStoreType);
try (InputStream keyStoreFile = Files.newInputStream(keystorePath)) {
keyStore.load(keyStoreFile,keyStorePassphrase.tochararray());
}
final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore,keyPassphrase.tochararray());
final Path truststorePath = Paths.get(trustStorePath);
final KeyStore trustStore = KeyStore.getInstance(trustStoreType);
try (InputStream trustStoreFile = Files.newInputStream(truststorePath)) {
trustStore.load(trustStoreFile,trustStorePassphrase.tochararray());
}
final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustStore);
return SslContextBuilder.forClient().keyManager(keyManagerFactory).trustManager(trustManagerFactory).build();
} catch (KeyStoreException | IOException | UnrecoverableKeyException | NoSuchAlgorithmException | CertificateException e) {
return null;
}
}
请问最简单的方法是什么?
谢谢
解决方法
Netty能够加载pem格式的私钥和证书作为密钥材料。它内置在SslContextBuilder中,请参见下面的示例:
SslContext sslContext = SslContextBuilder.forClient()
.keyManager(new File("/path/to/certificate.crt"),new File("/path/to/private.key"),"secret")
.build();
有关该方法的javadoc,请参见下文
/**
* Identifying certificate for this host. {@code keyCertChainFile} and {@code keyFile} may
* be {@code null} for client contexts,which disables mutual authentication.
*
* @param keyCertChainFile an X.509 certificate chain file in PEM format
* @param keyFile a PKCS#8 private key file in PEM format
* @param keyPassword the password of the {@code keyFile},or {@code null} if it's not
* password-protected
*/
public SslContextBuilder keyManager(File keyCertChainFile,File keyFile,String keyPassword) {
...
}
关于在不使用密钥库的情况下生成netty ssl上下文的第二个问题,我建议使用Bouncy城堡库创建私钥对作为密钥材料,您可以将其提供给netty sslcontext构建器。 请参见此处,以获取有关使用弹性城堡创建私钥对的参考:Generating keyPair using Bouncy Castle
有关可用于提供充气城堡生成的私钥和证书的方法,请参见下文
/**
* Identifying certificate for this host. {@code keyCertChain} and {@code key} may
* be {@code null} for client contexts,which disables mutual authentication.
*
* @param key a PKCS#8 private key
* @param keyCertChain an X.509 certificate chain
*/
public SslContextBuilder keyManager(PrivateKey key,Iterable<? extends X509Certificate> keyCertChain) {
return keyManager(key,toArray(keyCertChain,EMPTY_X509_CERTIFICATES));
}