下面列出了怎么用javax.net.ssl.SSLParameters的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public final SslContextFactory getInstance(String containerId, int port) {
TlsContext tlsContext = getTlsContext(containerId, port);
SSLContext sslContext = tlsContext.context();
SSLParameters parameters = tlsContext.parameters();
SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
sslContextFactory.setSslContext(sslContext);
sslContextFactory.setNeedClientAuth(parameters.getNeedClientAuth());
sslContextFactory.setWantClientAuth(parameters.getWantClientAuth());
setEnabledProtocols(sslContextFactory, sslContext, List.of(parameters.getProtocols()));
setEnabledCipherSuites(sslContextFactory, sslContext, List.of(parameters.getCipherSuites()));
return sslContextFactory;
}
public void handleEvent(final StreamConnection connection) {
try {
SSLEngine sslEngine = JsseSslUtils.createSSLEngine(sslContext, optionMap, destination);
SSLParameters params = sslEngine.getSSLParameters();
params.setServerNames(Collections.singletonList(new SNIHostName(destination.getHostString())));
sslEngine.setSSLParameters(params);
final SslConnection wrappedConnection = new UndertowSslConnection(connection, sslEngine, bufferPool);
if (!futureResult.setResult(wrappedConnection)) {
IoUtils.safeClose(connection);
} else {
ChannelListeners.invokeChannelListener(wrappedConnection, openListener);
}
} catch (Throwable e) {
futureResult.setException(new IOException(e));
}
}
/**
* Returns an array of anonym cipher suits supported by the default {@link SSLContext} or
* {@code null}, if accessing the default SSLContext fails.
* <p>
* {@link SslRMIClientSocketFactory} and {@link SslRMIServerSocketFactory} and therefore
* {@link AnonSslClientSocketFactory} and {@link AnonSslServerSocketFactory} use the
* default SSLContext to create SSL sockets (unless it is set explicitly).
* The default SSLContext is therefore used to access the supported chipher suites and filter
* the anonym ones.
* </p>
* Note: Getting the default SSLContext only works, if the system properties for keystore and
* truststore are not set or if they are set and the corresponding files exist.
*
* @return An array of anonym cipher suits supported by the default ssl context or {@code null},
* if accessing the default SSLContext fails.
*/
@Nullable
public static String[] getAnonymousCipherSuites() {
try {
SSLParameters parameters = SSLContext.getDefault().getSupportedSSLParameters();
List<String> anonymousCipherSuites = new ArrayList<>();
for (String supportedCipherSuite : parameters.getCipherSuites()) {
if (supportedCipherSuite.toLowerCase().contains("anon")) {
anonymousCipherSuites.add(supportedCipherSuite);
}
}
return anonymousCipherSuites.toArray(new String[anonymousCipherSuites.size()]);
}
catch (NoSuchAlgorithmException ex) {
LOG.error("Error accessing the default SSLContext.", ex);
return null;
}
}
@Test
public void createAnHTTPClient() throws NoSuchAlgorithmException {
HttpClient client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.proxy(ProxySelector.getDefault())
.followRedirects(HttpClient.Redirect.NEVER)
.authenticator(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("user", "pass".toCharArray());
}
})
.cookieHandler(new CookieManager())
.executor(Executors.newFixedThreadPool(2))
.priority(1)
.sslContext(SSLContext.getDefault())
.sslParameters(new SSLParameters())
.connectTimeout(Duration.ofSeconds(1))
.build();
assertThat(client.connectTimeout()).get().isEqualTo(Duration.ofSeconds(1));
}
public PjedisFactory(final String host, final int port, final int connectionTimeout,
final int soTimeout, final String password, final int database, final String clientName,
final boolean ssl, final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters,
final HostnameVerifier hostnameVerifier) {
this.hostAndPort.set(new HostAndPort(host, port));
this.connectionTimeout = connectionTimeout;
this.soTimeout = soTimeout;
this.password = password;
this.database = database;
this.clientName = clientName;
this.ssl = ssl;
this.sslSocketFactory = sslSocketFactory;
this.sslParameters = sslParameters;
this.hostnameVerifier = hostnameVerifier;
if (StringUtils.isNotEmpty(JedisPropsHolder.NAMESPACE.get())) {
this.namespace = JedisPropsHolder.NAMESPACE.get();
}
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void configureTlsExtensions(SSLSocket sslSocket, String hostname,
List<Protocol> protocols) {
try {
SSLParameters sslParameters = sslSocket.getSSLParameters();
List<String> names = alpnProtocolNames(protocols);
setProtocolMethod.invoke(sslParameters,
new Object[] {names.toArray(new String[names.size()])});
sslSocket.setSSLParameters(sslParameters);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new AssertionError();
}
}
static List<String> getSniHostNames(SSLParameters sslParameters) {
List<SNIServerName> names = sslParameters.getServerNames();
if (names == null || names.isEmpty()) {
return Collections.emptyList();
}
List<String> strings = new ArrayList<String>(names.size());
for (SNIServerName serverName : names) {
if (serverName instanceof SNIHostName) {
strings.add(((SNIHostName) serverName).getAsciiName());
} else {
throw new IllegalArgumentException("Only " + SNIHostName.class.getName()
+ " instances are supported, but found: " + serverName);
}
}
return strings;
}
@Override
public SSLEngine serverSslEngine(String peerHost, int peerPort) {
try {
SSLEngine sslEngine = upstreamServerSslContext.get().newEngine(ByteBufAllocator.DEFAULT, peerHost, peerPort);
// support SNI by setting the endpoint identification algorithm. this requires Java 7+.
SSLParameters sslParams = new SSLParameters();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
sslParams.setEndpointIdentificationAlgorithm("HTTPS");
}
sslEngine.setSSLParameters(sslParams);
return sslEngine;
} catch (RuntimeException e) {
throw new MitmException("Error creating SSLEngine for connection to upstream server: " + peerHost + ":" + peerPort, e);
}
}
private SSLEngine createSSLEngine(AmqpPort<?> port)
{
SSLEngine sslEngine = port.getSSLContext().createSSLEngine();
sslEngine.setUseClientMode(false);
SSLUtil.updateEnabledTlsProtocols(sslEngine, port.getTlsProtocolWhiteList(), port.getTlsProtocolBlackList());
SSLUtil.updateEnabledCipherSuites(sslEngine, port.getTlsCipherSuiteWhiteList(), port.getTlsCipherSuiteBlackList());
if(port.getTlsCipherSuiteWhiteList() != null && !port.getTlsCipherSuiteWhiteList().isEmpty())
{
SSLParameters sslParameters = sslEngine.getSSLParameters();
sslParameters.setUseCipherSuitesOrder(true);
sslEngine.setSSLParameters(sslParameters);
}
if(port.getNeedClientAuth())
{
sslEngine.setNeedClientAuth(true);
}
else if(port.getWantClientAuth())
{
sslEngine.setWantClientAuth(true);
}
return sslEngine;
}
private ChannelHandler getClientHandler(
X509Certificate trustedCertificate, PrivateKey privateKey, X509Certificate certificate) {
return new ChannelInitializer<LocalChannel>() {
@Override
protected void initChannel(LocalChannel ch) throws Exception {
SslContextBuilder sslContextBuilder =
SslContextBuilder.forClient().trustManager(trustedCertificate).sslProvider(sslProvider);
if (privateKey != null && certificate != null) {
sslContextBuilder.keyManager(privateKey, certificate);
}
SslHandler sslHandler =
sslContextBuilder.build().newHandler(ch.alloc(), SSL_HOST, SSL_PORT);
// Enable hostname verification.
SSLEngine sslEngine = sslHandler.engine();
SSLParameters sslParameters = sslEngine.getSSLParameters();
sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
sslEngine.setSSLParameters(sslParameters);
ch.pipeline().addLast(sslHandler);
}
};
}
final ServerSocket initSecure(int port) throws Exception {
ServerSocketFactory fac;
if (sslContext != null) {
fac = sslContext.getServerSocketFactory();
} else {
fac = SSLServerSocketFactory.getDefault();
}
SSLServerSocket se = (SSLServerSocket) fac.createServerSocket(port);
SSLParameters sslp = se.getSSLParameters();
sslp.setApplicationProtocols(new String[]{"h2"});
se.setSSLParameters(sslp);
se.setEnabledCipherSuites(se.getSupportedCipherSuites());
se.setEnabledProtocols(se.getSupportedProtocols());
// other initialisation here
return se;
}
@Override
protected void handlerAdded0(ChannelHandlerContext ctx) {
SSLEngine sslEngine = sslContext.newEngine(ctx.alloc(), host, port);
SSLParameters sslParams = sslEngine.getSSLParameters();
sslParams.setEndpointIdentificationAlgorithm("HTTPS");
sslEngine.setSSLParameters(sslParams);
ctx.pipeline().addBefore(ctx.name(), /* name= */ null, this.executor != null
? new SslHandler(sslEngine, false, this.executor)
: new SslHandler(sslEngine, false));
}
@Override
public void setApplicationProtocols(SSLParameters sslParameters, String[] protocols) {
try {
setApplicationProtocolsMethod.invoke(sslParameters, (Object) protocols);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new UnsupportedOperationException(e);
}
}
/**
* Applies SSLParameters to newly accepted connections.
*/
@Override
synchronized public void setSSLParameters(SSLParameters params) {
super.setSSLParameters(params);
// the super implementation does not handle the following parameters
identificationProtocol = params.getEndpointIdentificationAlgorithm();
algorithmConstraints = params.getAlgorithmConstraints();
preferLocalCipherSuites = params.getUseCipherSuitesOrder();
Collection<SNIMatcher> matchers = params.getSNIMatchers();
if (matchers != null) {
sniMatchers = params.getSNIMatchers();
}
}
SSLParameters getSSLParameters() {
SSLParameters params = new SSLParameters();
params.setAlgorithmConstraints(this.algorithmConstraints);
params.setProtocols(ProtocolVersion.toStringArray(enabledProtocols));
params.setCipherSuites(CipherSuite.namesOf(enabledCipherSuites));
switch (this.clientAuthType) {
case CLIENT_AUTH_REQUIRED:
params.setNeedClientAuth(true);
break;
case CLIENT_AUTH_REQUESTED:
params.setWantClientAuth(true);
break;
default:
params.setWantClientAuth(false);
}
params.setEndpointIdentificationAlgorithm(this.identificationProtocol);
if (serverNames.isEmpty() && !noSniExtension) {
// 'null' indicates none has been set
params.setServerNames(null);
} else {
params.setServerNames(this.serverNames);
}
if (sniMatchers.isEmpty() && !noSniMatcher) {
// 'null' indicates none has been set
params.setSNIMatchers(null);
} else {
params.setSNIMatchers(this.sniMatchers);
}
params.setApplicationProtocols(this.applicationProtocols);
params.setUseCipherSuitesOrder(this.preferLocalCipherSuites);
params.setEnableRetransmissions(this.enableRetransmissions);
params.setMaximumPacketSize(this.maximumPacketSize);
return params;
}
/**
* Create a Channel Initializer which is to to setup {@link ChannelPipeline}.
*/
@VisibleForTesting
ChannelInitializer<SocketChannel> getChannelInitializer(final PravegaNodeUri location,
final FlowHandler handler) {
final SslContext sslCtx = getSslContext();
return new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
if (sslCtx != null) {
SslHandler sslHandler = sslCtx.newHandler(ch.alloc(), location.getEndpoint(), location.getPort());
if (clientConfig.isValidateHostName()) {
SSLEngine sslEngine = sslHandler.engine();
SSLParameters sslParameters = sslEngine.getSSLParameters();
sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
sslEngine.setSSLParameters(sslParameters);
}
p.addLast(sslHandler);
}
p.addLast(
new ExceptionLoggingHandler(location.getEndpoint()),
new CommandEncoder(handler::getAppendBatchSizeTracker, metricNotifier),
new LengthFieldBasedFrameDecoder(WireCommands.MAX_WIRECOMMAND_SIZE, 4, 4),
new CommandDecoder(),
handler);
}
};
}
public TracingJedisPool(final GenericObjectPoolConfig poolConfig, final URI uri,
final int connectionTimeout,
final int soTimeout, final SSLSocketFactory sslSocketFactory,
final SSLParameters sslParameters,
final HostnameVerifier hostnameVerifier, TracingConfiguration tracingConfiguration) {
super(poolConfig, uri, connectionTimeout, soTimeout, sslSocketFactory, sslParameters,
hostnameVerifier);
this.tracingConfiguration = tracingConfiguration;
}
/**
* Returns the full trusted certificate chain found from {@code certs}.
*
* Throws {@link CertificateException} when no trusted chain can be found from {@code certs}.
*/
public List<X509Certificate> getTrustedChainForServer(X509Certificate[] certs,
String authType, Socket socket) throws CertificateException {
SSLSession session = null;
SSLParameters parameters = null;
if (socket instanceof SSLSocket) {
SSLSocket sslSocket = (SSLSocket) socket;
session = getHandshakeSessionOrThrow(sslSocket);
parameters = sslSocket.getSSLParameters();
}
return checkTrusted(certs, authType, session, parameters, false /* client auth */);
}
public TracingJedisPool(final GenericObjectPoolConfig poolConfig, final String host,
final int port,
final int timeout, final String password, final boolean ssl,
final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters,
final HostnameVerifier hostnameVerifier, TracingConfiguration tracingConfiguration) {
super(poolConfig, host, port, timeout, password, ssl, sslSocketFactory, sslParameters,
hostnameVerifier);
this.tracingConfiguration = tracingConfiguration;
}
@Override
public HttpServer createHttpServerInstance(int port) throws IOException {
try {
HttpsServer server = HttpsServer.create(new InetSocketAddress(port), 5);
server.setHttpsConfigurator(new HttpsConfigurator(sslContext) {
@Override
public void configure(HttpsParameters params) {
// get the remote address if needed
InetSocketAddress remote = params.getClientAddress();
SSLContext c = getSSLContext();
// get the default parameters
SSLParameters sslparams = c.getDefaultSSLParameters();
params.setSSLParameters(sslparams);
params.setProtocols(SSLUtils.getRecommendedProtocols());
params.setCipherSuites(SSLUtils.getRecommendedCiphers());
// statement above could throw IAE if any params invalid.
// eg. if app has a UI and parameters supplied by a user.
}
});
s_logger.info("create HTTPS server instance on port: " + port);
return server;
} catch (Exception ioe) {
s_logger.error(ioe.toString(), ioe);
}
return null;
}
@Override
public synchronized void setSSLParameters(javax.net.ssl.SSLParameters params) {
conContext.sslConfig.setSSLParameters(params);
if (conContext.sslConfig.maximumPacketSize != 0) {
conContext.outputRecord.changePacketSize(
conContext.sslConfig.maximumPacketSize);
}
}
public void enableTLSv12UsingSSLParameters() throws UnknownHostException, IOException {
SSLSocketFactory socketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sslSocket = (SSLSocket) socketFactory.createSocket(url.trim(), port);
SSLParameters params = new SSLParameters();
params.setProtocols(new String[] { "TLSv1.2" });
sslSocket.setSSLParameters(params);
sslSocket.startHandshake();
handleCommunication(sslSocket, "SSLSocketFactory-SSLParameters");
}
public PjedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port,
int timeout, final String password, final boolean ssl,
final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters,
final HostnameVerifier hostnameVerifier) {
this(poolConfig, host, port, timeout, password, Protocol.DEFAULT_DATABASE, null, ssl,
sslSocketFactory, sslParameters, hostnameVerifier);
}
@Override
public SSLEngine createSSLEngine(String peerHost, int peerPort, Mode mode) {
SslContext context = mode == Mode.CLIENT ? nettyClientSslContext : nettyServerSslContext;
SSLEngine sslEngine = context.newEngine(ByteBufAllocator.DEFAULT, peerHost, peerPort);
if (mode == Mode.CLIENT) {
SSLParameters sslParams = sslEngine.getSSLParameters();
sslParams.setEndpointIdentificationAlgorithm(endpointIdentification);
sslEngine.setSSLParameters(sslParams);
}
return sslEngine;
}
public PjedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port,
final int connectionTimeout, final int soTimeout, final String password, final int database,
final String clientName, final boolean ssl, final SSLSocketFactory sslSocketFactory,
final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) {
super(poolConfig, new PjedisFactory(host, port, connectionTimeout, soTimeout, password,
database, clientName, ssl, sslSocketFactory, sslParameters, hostnameVerifier));
}
public PjedisPool(final GenericObjectPoolConfig poolConfig, final URI uri,
final int connectionTimeout, final int soTimeout, final SSLSocketFactory sslSocketFactory,
final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) {
super(poolConfig, new PjedisFactory(uri, connectionTimeout, soTimeout, null,
(uri.getScheme() !=null && uri.getScheme().equals("rediss")), sslSocketFactory,
sslParameters, hostnameVerifier));
}
@Override
public SSLEngine serverSslEngine(String peerHost, int peerPort) {
try {
SSLEngine sslEngine = upstreamServerSslContext.get().newEngine(ByteBufAllocator.DEFAULT, peerHost, peerPort);
// support SNI by setting the endpoint identification algorithm. this requires Java 7+.
SSLParameters sslParams = new SSLParameters();
sslParams.setEndpointIdentificationAlgorithm("HTTPS");
sslEngine.setSSLParameters(sslParams);
return sslEngine;
} catch (RuntimeException e) {
throw new MitmException("Error creating SSLEngine for connection to upstream server: " + peerHost + ":" + peerPort, e);
}
}
public TracingJedisPool(final GenericObjectPoolConfig poolConfig, final String host,
final int port, final int timeout,
final String password, final int database, final boolean ssl,
final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters,
final HostnameVerifier hostnameVerifier, TracingConfiguration tracingConfiguration) {
super(poolConfig, host, port, timeout, password, database, ssl, sslSocketFactory, sslParameters,
hostnameVerifier);
this.tracingConfiguration = tracingConfiguration;
}
public TracingJedisPool(final GenericObjectPoolConfig poolConfig, final String host,
final int port, final boolean ssl,
final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters,
final HostnameVerifier hostnameVerifier, TracingConfiguration tracingConfiguration) {
super(poolConfig, host, port, ssl, sslSocketFactory, sslParameters, hostnameVerifier);
this.tracingConfiguration = tracingConfiguration;
}
/**
* Applies SSLParameters to newly accepted connections.
*/
@Override
synchronized public void setSSLParameters(SSLParameters params) {
super.setSSLParameters(params);
// the super implementation does not handle the following parameters
identificationProtocol = params.getEndpointIdentificationAlgorithm();
algorithmConstraints = params.getAlgorithmConstraints();
preferLocalCipherSuites = params.getUseCipherSuitesOrder();
Collection<SNIMatcher> matchers = params.getSNIMatchers();
if (matchers != null) {
sniMatchers = params.getSNIMatchers();
}
}