本文整理汇总了Java中javax.net.ssl.SSLContext类的典型用法代码示例。如果您正苦于以下问题:Java SSLContext类的具体用法?Java SSLContext怎么用?Java SSLContext使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
SSLContext类属于javax.net.ssl包,在下文中一共展示了SSLContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getSocketFactory
import javax.net.ssl.SSLContext; //导入依赖的package包/类
private SSLSocketFactory getSocketFactory() {
try {
Security.addProvider(new BouncyCastleProvider());
TrustManagerFactory trustManagerFactory = createAndInitTrustManagerFactory();
KeyManagerFactory keyManagerFactory = createAndInitKeyManagerFactory();
SSLContext context = SSLContext.getInstance(TLS_VERSION);
context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
return context.getSocketFactory();
} catch (Exception e) {
log.error("[{}:{}:{}:{}] Creating TLS factory failed!", caCert, cert, privateKey, password, e);
throw new RuntimeException("Creating TLS factory failed!", e);
}
}
示例2: newSSLContext
import javax.net.ssl.SSLContext; //导入依赖的package包/类
public static SSLContext newSSLContext(final KeyStore ks, final String password,
final String ksAlgorithm) throws InvalidSSLConfig {
try {
// Get a KeyManager and initialize it
final KeyManagerFactory kmf = KeyManagerFactory.getInstance(ksAlgorithm);
kmf.init(ks, password.toCharArray());
// Get a TrustManagerFactory with the DEFAULT KEYSTORE, so we have all the certificates in cacerts trusted
final TrustManagerFactory tmf = TrustManagerFactory.getInstance(ksAlgorithm);
tmf.init((KeyStore) null);
// Get the SSLContext to help create SSLSocketFactory
final SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
return sslContext;
} catch (final GeneralSecurityException e) {
throw new InvalidSSLConfig(e);
}
}
示例3: restTemplate
import javax.net.ssl.SSLContext; //导入依赖的package包/类
@Bean
public RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(null, new TrustSelfSignedStrategy())
.build();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(sslConnectionSocketFactory)
.build();
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
return new RestTemplate(requestFactory);
}
示例4: emmit
import javax.net.ssl.SSLContext; //导入依赖的package包/类
private void emmit(FlowableEmitter<Message> emitter, String roomId) throws Exception {
SSLContext sslCtx = SSLContext.getDefault();
SSLEngine sslEngine = sslCtx.createSSLEngine("stream.gitter.im", 443);
sslEngine.setUseClientMode(true);
HttpClient
.newClient("stream.gitter.im", 443)
.secure(sslEngine)
.createGet("/v1/rooms/" + roomId + "/chatMessages")
.addHeader("Authorization", "Bearer 3cd4820adf59b6a7116f99d92f68a1b786895ce7")
.flatMap(HttpClientResponse::getContent)
.filter(bb -> bb.capacity() > 2)
.map(MessageEncoder::mapToMessage)
.doOnNext(m -> System.out.println("Log Emit: " + m))
.subscribe(emitter::onNext, emitter::onError, emitter::onComplete);
}
示例5: SslHandlerFactory
import javax.net.ssl.SSLContext; //导入依赖的package包/类
public SslHandlerFactory(AmqpServerConfiguration configuration) throws KeyStoreException, IOException,
CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException {
KeyStore keyStore = getKeyStore(configuration.getSsl().getKeyStore().getType(),
configuration.getSsl().getKeyStore().getLocation(),
configuration.getSsl().getKeyStore().getPassword());
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(configuration.getSsl()
.getKeyStore()
.getCertType());
keyManagerFactory.init(keyStore, configuration.getSsl().getKeyStore().getPassword().toCharArray());
KeyStore trustStore = getKeyStore(configuration.getSsl().getTrustStore().getType(),
configuration.getSsl().getTrustStore().getLocation(),
configuration.getSsl().getTrustStore().getPassword());
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(configuration.getSsl()
.getTrustStore()
.getCertType());
trustManagerFactory.init(trustStore);
sslContext = SSLContext.getInstance(configuration.getSsl().getProtocol());
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
}
示例6: buildCertificateIgnoringSslContext
import javax.net.ssl.SSLContext; //导入依赖的package包/类
/**
* Will create a certificate-ignoring {@link SSLContext}. Please use with utmost caution as it undermines security,
* but may be useful in certain testing or development scenarios.
*
* @return The SSLContext
*/
public static SSLContext buildCertificateIgnoringSslContext() {
try {
return SSLContexts
.custom()
.loadTrustMaterial(new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
return true;
}
})
.build();
}
catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
throw new IllegalStateException("Unexpected exception while building the certificate-ignoring SSLContext.", e);
}
}
示例7: prepareConnection
import javax.net.ssl.SSLContext; //导入依赖的package包/类
private HttpURLConnection prepareConnection(Request request) throws IOException, RequestFailedException {
final URL url = new URL(endpoint, MethodNameConverter.convert(request));
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if (this.ignoreSllExceptions && connection instanceof HttpsURLConnection) {
HttpsURLConnection sslConnection = (HttpsURLConnection) connection;
try {
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[]{new TrustEverythingManager()}, new SecureRandom());
sslConnection.setHostnameVerifier(new DisabledHostnameVerifier());
sslConnection.setSSLSocketFactory(sslContext.getSocketFactory());
} catch (Exception e) {
throw new RequestFailedException(e);
}
}
connection.setRequestMethod("POST");
if (this.username != null && this.password != null) {
String authorization = Base64.getEncoder().encodeToString((username + ":" + password).getBytes(StandardCharsets.UTF_8));
connection.addRequestProperty("Authorization", "Basic " + authorization);
}
return connection;
}
示例8: createUrlConnection
import javax.net.ssl.SSLContext; //导入依赖的package包/类
public static synchronized HttpURLConnection createUrlConnection(final String urlStr) throws IOException, GeneralSecurityException {
final URL url = new URL(urlStr);
SSLContext sslCtx = createSslContext();
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
if (urlConnection instanceof HttpsURLConnection) {
((HttpsURLConnection) urlConnection).setSSLSocketFactory(sslCtx.getSocketFactory());
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return hostname.equalsIgnoreCase(url.getHost());
}
};
((HttpsURLConnection) urlConnection).setHostnameVerifier(hostnameVerifier);
}
urlConnection.setConnectTimeout(200);
return urlConnection;
}
示例9: ApacheThriftMethodInvoker
import javax.net.ssl.SSLContext; //导入依赖的package包/类
public ApacheThriftMethodInvoker(
ListeningExecutorService executorService,
ListeningScheduledExecutorService delayService,
TTransportFactory transportFactory,
TProtocolFactory protocolFactory,
Duration connectTimeout,
Duration requestTimeout,
Optional<HostAndPort> socksProxy,
Optional<SSLContext> sslContext)
{
this.executorService = requireNonNull(executorService, "executorService is null");
this.delayService = requireNonNull(delayService, "delayService is null");
this.transportFactory = requireNonNull(transportFactory, "transportFactory is null");
this.protocolFactory = requireNonNull(protocolFactory, "protocolFactory is null");
this.connectTimeoutMillis = Ints.saturatedCast(requireNonNull(connectTimeout, "connectTimeout is null").toMillis());
this.requestTimeoutMillis = Ints.saturatedCast(requireNonNull(requestTimeout, "requestTimeout is null").toMillis());
this.socksProxy = requireNonNull(socksProxy, "socksProxy is null");
this.sslContext = requireNonNull(sslContext, "sslContext is null");
}
示例10: usingOkHttp3
import javax.net.ssl.SSLContext; //导入依赖的package包/类
static ClientHttpRequestFactory usingOkHttp3(ClientOptions options)
throws IOException, GeneralSecurityException {
SSLSocketFactory socketFactory = SSLContext.getDefault().getSocketFactory();
X509TrustManager trustManager = getTrustManager();
Builder builder = new Builder().sslSocketFactory(socketFactory, trustManager);
if (options.getConnectionTimeout() != null) {
builder.connectTimeout(options.getConnectionTimeout(), TimeUnit.MILLISECONDS);
}
if (options.getReadTimeout() != null) {
builder.readTimeout(options.getReadTimeout(), TimeUnit.MILLISECONDS);
}
return new OkHttp3ClientHttpRequestFactory(builder.build());
}
示例11: httpsWithCustomTrustManager
import javax.net.ssl.SSLContext; //导入依赖的package包/类
@Test public void httpsWithCustomTrustManager() throws Exception {
RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier();
RecordingTrustManager trustManager = new RecordingTrustManager(sslClient.trustManager);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] { trustManager }, null);
urlFactory.setClient(urlFactory.client().newBuilder()
.hostnameVerifier(hostnameVerifier)
.sslSocketFactory(sslContext.getSocketFactory(), trustManager)
.build());
server.useHttps(sslClient.socketFactory, false);
server.enqueue(new MockResponse().setBody("ABC"));
server.enqueue(new MockResponse().setBody("DEF"));
server.enqueue(new MockResponse().setBody("GHI"));
URL url = server.url("/").url();
assertContent("ABC", urlFactory.open(url));
assertContent("DEF", urlFactory.open(url));
assertContent("GHI", urlFactory.open(url));
assertEquals(Arrays.asList("verify " + server.getHostName()), hostnameVerifier.calls);
assertEquals(Arrays.asList("checkServerTrusted [CN=" + server.getHostName() + " 1]"),
trustManager.calls);
}
示例12: setSSLContext
import javax.net.ssl.SSLContext; //导入依赖的package包/类
public void setSSLContext(final SSLContext sslContext) {
SchemeRegistry registry = getConnectionManager().getSchemeRegistry();
registry.unregister("https");
registry.register(new Scheme("https", 443, new SSLSocketFactory(sslContext)));
/*
if (DefaultServer.getHostAddress(DefaultServer.DEFAULT).equals("localhost")) {
registry.register(new Scheme("https", 443, new SSLSocketFactory(sslContext)));
registry.register(new Scheme("https", DefaultServer.getHostSSLPort("default"), new SSLSocketFactory(sslContext)));
} else {
registry.register(new Scheme("https", 443, new SSLSocketFactory(sslContext, NO_OP_VERIFIER)));
registry.register(new Scheme("https", DefaultServer.getHostSSLPort("default"), new SSLSocketFactory(sslContext, NO_OP_VERIFIER)));
}
*/
}
示例13: auth
import javax.net.ssl.SSLContext; //导入依赖的package包/类
private void auth(String mechanism) throws IOException {
mechanism = mechanism.toUpperCase();
if(mechanism.equals("TLS") || mechanism.equals("TLS-C") ||
mechanism.equals("SSL") || mechanism.equals("TLS-P")) {
// No need to distinguish between TLS and SSL, as the protocol self-negotiate its level
SSLContext ssl = con.getServer().getSSLContext();
if(ssl == null) {
con.sendResponse(431, "TLS/SSL is not available");
} else if(con.isSSLEnabled()) {
con.sendResponse(503, "TLS/SSL is already enabled");
} else {
con.sendResponse(234, "Enabling TLS/SSL...");
con.enableSSL(ssl);
}
} else {
con.sendResponse(502, "Unsupported mechanism");
}
}
示例14: WebSocketClient
import javax.net.ssl.SSLContext; //导入依赖的package包/类
public WebSocketClient(SSLContext ssl, String hostname, int httpsPort, int wssPort, boolean doLogin,
String username, String password, boolean hostVerificationEnabled, int bufferSize) {
this.ssl = ssl;
this.hostname = hostname;
this.httpsPort = httpsPort;
this.wssPort = wssPort;
this.doLogin = doLogin;
this.username = username;
this.password = password;
this.hostVerificationEnabled = hostVerificationEnabled;
this.bufferSize = bufferSize;
Preconditions.checkNotNull(hostname, "%s must be supplied", "host name");
Preconditions.checkNotNull(httpsPort, "%s must be supplied", "HTTPS port");
Preconditions.checkNotNull(wssPort, "%s must be supplied", "WSS port");
if (doLogin
&& ((StringUtils.isEmpty(username) && !StringUtils.isEmpty(password) || (!StringUtils.isEmpty(username) && StringUtils
.isEmpty(password))))) {
throw new IllegalArgumentException("Both username and password must be empty or non-empty");
}
}
示例15: initSsl
import javax.net.ssl.SSLContext; //导入依赖的package包/类
private void initSsl() throws Exception {
TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
KeyStore ts = KeyStore.getInstance("JKS");
ts.load(new FileInputStream(tsLocation), tsPwd);
tmFactory.init(ts);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream(ksLocation), ksPwd);
kmf.init(ks, ksPwd);
sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), tmFactory.getTrustManagers(), null);
}