本文整理汇总了Java中javax.net.ssl.SSLContext.init方法的典型用法代码示例。如果您正苦于以下问题:Java SSLContext.init方法的具体用法?Java SSLContext.init怎么用?Java SSLContext.init使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类javax.net.ssl.SSLContext
的用法示例。
在下文中一共展示了SSLContext.init方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: afterPropertiesSet
import javax.net.ssl.SSLContext; //导入方法依赖的package包/类
@PostConstruct
public void afterPropertiesSet() throws Exception {
RegistryBuilder<ConnectionSocketFactory> schemeRegistry = RegistryBuilder.create();
schemeRegistry.register("http", PlainConnectionSocketFactory.getSocketFactory());
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(new KeyManager[0], new TrustManager[]{new SimpleTrustManager()}, null);
SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslcontext);
schemeRegistry.register("https", sf);
pool = new PoolingHttpClientConnectionManager(schemeRegistry.build());
pool.setMaxTotal(maxConnection);
pool.setDefaultMaxPerRoute(maxConnection);
pool.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(sotimeout).build());
}
示例2: getTrustedSslContext
import javax.net.ssl.SSLContext; //导入方法依赖的package包/类
/**
* Gets the trusted ssl context.
*
* @param trustStoreFile the trust store file
* @param trustStorePassword the trust store password
* @param trustStoreType the trust store type
* @return the trusted ssl context
*/
private static SSLContext getTrustedSslContext(final File trustStoreFile, final String trustStorePassword,
final String trustStoreType) {
try {
if (!trustStoreFile.exists() || !trustStoreFile.canRead()) {
throw new FileNotFoundException("Truststore file cannot be located at "
+ trustStoreFile.getCanonicalPath());
}
final KeyStore casTrustStore = KeyStore.getInstance(trustStoreType);
final char[] trustStorePasswordCharArray = trustStorePassword.toCharArray();
try (final FileInputStream casStream = new FileInputStream(trustStoreFile)) {
casTrustStore.load(casStream, trustStorePasswordCharArray);
}
final String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
final X509KeyManager customKeyManager = getKeyManager("PKIX", casTrustStore, trustStorePasswordCharArray);
final X509KeyManager jvmKeyManager = getKeyManager(defaultAlgorithm, null, null);
final X509TrustManager customTrustManager = getTrustManager("PKIX", casTrustStore);
final X509TrustManager jvmTrustManager = getTrustManager(defaultAlgorithm, null);
final KeyManager[] keyManagers = {
new CompositeX509KeyManager(Arrays.asList(jvmKeyManager, customKeyManager))
};
final TrustManager[] trustManagers = {
new CompositeX509TrustManager(Arrays.asList(jvmTrustManager, customTrustManager))
};
final SSLContext context = SSLContexts.custom().useSSL().build();
context.init(keyManagers, trustManagers, null);
return context;
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
throw new RuntimeException(e);
}
}
示例3: getCertificatesFromSocket
import javax.net.ssl.SSLContext; //导入方法依赖的package包/类
/**
* @param host the host
* @param port the port
*
* @return array with all server-side certificates obtained from direct socket connection
*/
public static synchronized Certificate[] getCertificatesFromSocket( String host, String port ) {
TrustManager[] trustAllCerts = new TrustManager[]{ new DefaultTrustManager() {} };
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(host, Integer.valueOf(port));
sslSocket.startHandshake();
return sslSocket.getSession().getPeerCertificates();
} catch (Exception e) {
throw new RuntimeException("Could not get certificate of secure socket to " + host + ":" + port + ".!", e);
}
}
示例4: test
import javax.net.ssl.SSLContext; //导入方法依赖的package包/类
/**
* The parameter passed is the user enforced protocol. Does not catch
* NoSuchAlgorithmException, WrongProperty test will use it.
*/
public void test(String expectedContextProto,
String[] expectedDefaultProtos) throws NoSuchAlgorithmException {
SSLContext context = null;
try {
if (expectedContextProto != null) {
context = SSLContext.getInstance(expectedContextProto);
context.init(null, null, null);
} else {
context = SSLContext.getDefault();
}
printContextDetails(context);
} catch (KeyManagementException ex) {
error(null, ex);
}
validateContext(expectedContextProto, expectedDefaultProtos, context);
}
示例5: createTopicsIfNecessary
import javax.net.ssl.SSLContext; //导入方法依赖的package包/类
public void createTopicsIfNecessary( String... topics ) throws Exception{
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, null, null);
for( String topic : topics ){
URL messageHubUrl = new URL( getConfig(MessageHubConfig.MESSAGEHUB_REST_URL) + "/admin/topics" );
HttpsURLConnection con = (HttpsURLConnection) messageHubUrl.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("X-Auth-Token", getConfig(MessageHubConfig.MESSAGEHUB_API_KEY));
con.setRequestProperty("Accept", "application/json");
con.setRequestMethod("POST");
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write( "{\"name\":\"" + topic + "\"}" );
wr.flush();
int res = con.getResponseCode();
switch (res){
case 200:
case 202:
System.out.println("Successfully created topic: " + topic);
break;
case 422:
case 403:
System.out.println("Topic already exists in the server: " + topic);
break;
default:
throw new IllegalStateException("Error when trying to create topic: " + res + " Reason: " + con.getResponseMessage());
}
}
}
示例6: connectWSS
import javax.net.ssl.SSLContext; //导入方法依赖的package包/类
public boolean connectWSS(boolean reconnect) {
try {
if (reconnect) {
com.gmt2001.Console.out.println("Reconnecting to Twitch Websockets chat [" + this.uri.getHost() + "]");
} else {
//com.gmt2001.Console.out.println("Connecting to Twitch Websockets chat [" + this.uri.getHost() + "]");
}
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, null, null);
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
this.setSocket(sslSocketFactory.createSocket());
this.twitchWSIRCParser = new IRCParser(this.getConnection(), channelName, channel, session, eventBus, ownerName);
this.connect();
return true;
} catch (Exception ex) {
com.gmt2001.Console.err.println(ex.getMessage());
return false;
}
}
示例7: build
import javax.net.ssl.SSLContext; //导入方法依赖的package包/类
public SSLContext build() throws NoSuchAlgorithmException, KeyManagementException {
final SSLContext sslcontext = SSLContext.getInstance(
this.protocol != null ? this.protocol : TLS);
sslcontext.init(
!keymanagers.isEmpty() ? keymanagers.toArray(new KeyManager[keymanagers.size()]) : null,
!trustmanagers.isEmpty() ? trustmanagers.toArray(new TrustManager[trustmanagers.size()]) : null,
secureRandom);
return sslcontext;
}
示例8: WebSocketClient
import javax.net.ssl.SSLContext; //导入方法依赖的package包/类
public WebSocketClient(DiscordAPIImpl api, String url) {
super(URI.create(url));
if (url.startsWith("wss"))
{
try
{
SSLContext sslContext;
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, null, null);
this.setWebSocketFactory(new DefaultSSLWebSocketClientFactory(sslContext));
}
catch (NoSuchAlgorithmException | KeyManagementException e)
{
e.printStackTrace();
}
}
this.api = api;
readyPoll = new ReadyPoll(api);
banPoll = new BanPoll(api);
addUserPoll = new AddUserPoll(api);
messagePoll = new MessagePoll(api);
kickedPoll = new KickPoll(api);
typingPoll = new TypingPoll(api);
newContactOrGroupPoll = new NewContactOrGroupPoll(api);
statusPoll = new StatusPoll(api);
updateSettings = new UpdateSettings(api);
channelRemovePoll = new ChannelRemove(api);
channelUpdatePoll = new ChannelUpdatePoll(api);
guildAddPoll = new GuildAdd(api);
userUpdatePoll = new UserUpdatePoll(api);
deletePoll = new DeleteMessagePoll(api);
webhookPoll = new WebhookUpdatePoll(api);
this.connect();
}
示例9: post
import javax.net.ssl.SSLContext; //导入方法依赖的package包/类
/**
* 鍙戦�丳ost璇锋眰
* @param url
* @param params
* @return
* @throws IOException
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static String post(String url, String params,Boolean https) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
StringBuffer bufferRes = null;
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 浠庝笂杩癝SLContext瀵硅薄涓緱鍒癝SLSocketFactory瀵硅薄
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL urlGet = new URL(url);
HttpsURLConnection http = (HttpsURLConnection) urlGet.openConnection();
// 杩炴帴瓒呮椂
http.setConnectTimeout(50000);
// 璇诲彇瓒呮椂 --鏈嶅姟鍣ㄥ搷搴旀瘮杈冩參锛屽澶ф椂闂�
http.setReadTimeout(50000);
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setSSLSocketFactory(ssf);
http.setHostnameVerifier(new Verifier());
http.setDoOutput(true);
http.setDoInput(true);
http.connect();
OutputStream out = http.getOutputStream();
out.write(params.getBytes("UTF-8"));
out.flush();
out.close();
InputStream in = http.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
String valueString = null;
bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null){
bufferRes.append(valueString);
}
in.close();
if (http != null) {
// 鍏抽棴杩炴帴
http.disconnect();
}
return bufferRes.toString();
}
示例10: getPreferredSslContext
import javax.net.ssl.SSLContext; //导入方法依赖的package包/类
private static SSLContext getPreferredSslContext() {
try {
final SSLContext sslcontext = SSLContext.getInstance("TLS");
// http://download.java.net/jdk9/docs/technotes/guides/security/jsse/JSSERefGuide.html
sslcontext.init(null, null, null);
return sslcontext;
} catch (final NoSuchAlgorithmException | KeyManagementException ex) {
throw new SSLInitializationException(ex.getMessage(), ex);
}
}
示例11: initSSLcontext
import javax.net.ssl.SSLContext; //导入方法依赖的package包/类
public static SSLSocketFactory initSSLcontext(TrustManager[] trustManagers) throws NoSuchAlgorithmException,
KeyManagementException {
SSLSocketFactory sslSocketfactory = null;
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, trustManagers, null);
sslSocketfactory = context.getSocketFactory();
return sslSocketfactory;
}
示例12: initChannel
import javax.net.ssl.SSLContext; //导入方法依赖的package包/类
@Override
protected void initChannel(Channel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
OFChannelHandler handler = new OFChannelHandler(
switchManager,
connectionListener,
pipeline,
debugCounters,
timer,
ofBitmaps,
defaultFactory);
if (keyStore != null && keyStorePassword != null) {
try {
/* Set up factories and stores. */
TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
KeyStore tmpKS = null;
tmFactory.init(tmpKS);
/* Use keystore/pass defined in properties file. */
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream(keyStore), keyStorePassword.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, keyStorePassword.toCharArray());
KeyManager[] km = kmf.getKeyManagers();
TrustManager[] tm = tmFactory.getTrustManagers();
/* Set up SSL prereqs for Netty. */
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(km, tm, null);
SSLEngine sslEngine = sslContext.createSSLEngine();
/* We are the server and we will create secure sessions. */
sslEngine.setUseClientMode(false);
sslEngine.setEnableSessionCreation(true);
/* These are redundant (default), but for clarity... */
sslEngine.setEnabledProtocols(sslEngine.getSupportedProtocols());
sslEngine.setEnabledCipherSuites(sslEngine.getSupportedCipherSuites());
/* First, decrypt w/handler+engine; then, proceed with rest of handlers. */
pipeline.addLast(PipelineHandler.SSL_TLS_ENCODER_DECODER, new SslHandler(sslEngine));
log.info("SSL OpenFlow socket initialized and handler ready for switch.");
} catch (Exception e) { /* There are lots of possible exceptions to catch, so this should get them all. */
log.error("Exception initializing SSL OpenFlow socket: {}", e.getMessage());
throw e; /* If we wanted secure but didn't get it, we should bail. */
}
}
pipeline.addLast(PipelineHandler.OF_MESSAGE_DECODER,
new OFMessageDecoder());
pipeline.addLast(PipelineHandler.OF_MESSAGE_ENCODER,
new OFMessageEncoder());
pipeline.addLast(PipelineHandler.MAIN_IDLE,
new IdleStateHandler(PipelineIdleReadTimeout.MAIN,
PipelineIdleWriteTimeout.MAIN,
0));
pipeline.addLast(PipelineHandler.READ_TIMEOUT, new ReadTimeoutHandler(30));
pipeline.addLast(PipelineHandler.CHANNEL_HANDSHAKE_TIMEOUT,
new HandshakeTimeoutHandler(
handler,
timer,
PipelineHandshakeTimeout.CHANNEL));
pipeline.addLast(PipelineHandler.CHANNEL_HANDLER, handler);
}
示例13: getSSLSocketFactory
import javax.net.ssl.SSLContext; //导入方法依赖的package包/类
public static SSLSocketFactory getSSLSocketFactory () throws KeyManagementException, NoSuchProviderException, NoSuchAlgorithmException {
if(VISSLFACTORY == null) {
TrustManager[] tm = {new MyX509TrustManager()};
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new SecureRandom());
VISSLFACTORY = sslContext.getSocketFactory();
}
return VISSLFACTORY;
}
示例14: initSSLSocketFactory
import javax.net.ssl.SSLContext; //导入方法依赖的package包/类
/**
* Configures an {@link SSLContext} on the specified {@link OkHttpClient.Builder}, taking into account
* the trust store specified by {@link EndpointConnector#keystorePath()} and {@link EndpointConnector#keystorePassword()}}
*/
private static void initSSLSocketFactory(EndpointConnector connector, OkHttpClient.Builder builder) {
char[] keystorePassword = byteToCharArray(connector.keystorePassword());
try {
// initialize keystore
// the default type is 'jks'; however, this can be changed by updating the `keystore.type` property
// in `$JAVA_HOME/lib/security/java.security`
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(new FileInputStream(connector.keystorePath()), keystorePassword);
// setup trust manager factory
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keystore);
X509TrustManager trustManager = (X509TrustManager)trustManagerFactory.getTrustManagers()[0];
// setup key manager factory
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keystore, keystorePassword);
// initialize an SSL context using the same protocol as the default and init
SSLContext sslContext = SSLContext.getInstance(connector.sslContextAlgorithm());
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
// set socket factory
builder.sslSocketFactory(sslContext.getSocketFactory(), trustManager);
} catch (IOException |CertificateException |UnrecoverableKeyException |NoSuchAlgorithmException |KeyStoreException |KeyManagementException e) {
// rethrow as RTE, since we cannot continue if mutual auth was expected but could not be initialized
throw new RuntimeException("Unexpected exception configuring mutual authentication for " + connector.id(), e);
} finally {
// clear password after using it
Arrays.fill(keystorePassword, (char)0);
}
}
示例15: createSSLContext
import javax.net.ssl.SSLContext; //导入方法依赖的package包/类
public static SSLContext createSSLContext()
{
try
{
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(new FileInputStream("A2KeyStore.jks"), "1234567890".toCharArray());
// Create key manager
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
keyManagerFactory.init(keyStore, "1234567890".toCharArray());
KeyManager[] km = keyManagerFactory.getKeyManagers();
// Create trust manager
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
trustManagerFactory.init(keyStore);
TrustManager[] tm = trustManagerFactory.getTrustManagers();
// Initialize SSLContext
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(km, tm, null);
return sslContext;
}
catch (Exception ex)
{
ex.printStackTrace();
}
return null;
}