类javax.net.ssl.SSLContext源码实例Demo

下面列出了怎么用javax.net.ssl.SSLContext的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: vespa   文件: AthenzCredentialsService.java
AthenzCredentials updateCredentials(SignedIdentityDocument document, SSLContext sslContext) {
    KeyPair newKeyPair = KeyUtils.generateKeypair(KeyAlgorithm.RSA);
    Pkcs10Csr csr = csrGenerator.generateInstanceCsr(
            tenantIdentity,
            document.providerUniqueId(),
            document.ipAddresses(),
            newKeyPair);

    try (ZtsClient ztsClient = new DefaultZtsClient(ztsEndpoint, sslContext)) {
        InstanceIdentity instanceIdentity =
                ztsClient.refreshInstance(
                        configserverIdentity,
                        tenantIdentity,
                        document.providerUniqueId().asDottedString(),
                        csr);
        X509Certificate certificate = instanceIdentity.certificate();
        writeCredentialsToDisk(newKeyPair.getPrivate(), certificate, document);
        return new AthenzCredentials(certificate, newKeyPair, document);
    }
}
 
源代码2 项目: ballerina-message-broker   文件: HttpClient.java
public HttpClient(Configuration configuration) {
    this.url = configuration.getUrl() + BROKER_CONNECTION_URL_SUFFIX;
    this.encodedCredentials = configuration.getEncodedCredentials();

    // turn off SSL verification
    try {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509UntrustManagerImpl() };

        // Install the all-trusting trust manager
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = (hostname, session) -> true;

        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    } catch (KeyManagementException | NoSuchAlgorithmException e) {
        BrokerClientException exception = new BrokerClientException();
        exception.addMessage("error initializing the connection");
        exception.addMessage(e.getMessage());
        throw exception;
    }
}
 
源代码3 项目: vespa   文件: SimpleHttpClient.java
public SimpleHttpClient(SSLContext sslContext, List<String> enabledProtocols, List<String> enabledCiphers,
                        int listenPort, boolean useCompression) {
    HttpClientBuilder builder = HttpClientBuilder.create();
    if (!useCompression) {
        builder.disableContentCompression();
    }
    if (sslContext != null) {
        SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(
                sslContext,
                toArray(enabledProtocols),
                toArray(enabledCiphers),
                new DefaultHostnameVerifier());
        builder.setSSLSocketFactory(sslConnectionFactory);

        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslConnectionFactory)
                .build();
        builder.setConnectionManager(new BasicHttpClientConnectionManager(registry));
        scheme = "https";
    } else {
        scheme = "http";
    }
    this.delegate = builder.build();
    this.listenPort = listenPort;
}
 
源代码4 项目: cloudstack   文件: Link.java
public static SSLContext initManagementSSLContext(final CAService caService) throws GeneralSecurityException, IOException {
    if (caService == null) {
        throw new CloudRuntimeException("CAService is not available to load/get management server keystore");
    }
    final KeyStore ks = caService.getManagementKeyStore();
    char[] passphrase = caService.getKeyStorePassphrase();

    final TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(ks);
    final TrustManager[] tms = tmf.getTrustManagers();

    final KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks, passphrase);

    final SSLContext sslContext = SSLUtils.getSSLContext();
    sslContext.init(kmf.getKeyManagers(), tms, new SecureRandom());
    return sslContext;
}
 
源代码5 项目: openjdk-jdk9   文件: ServerIdentityTest.java
private static void initialize(String[] args) throws Exception {
    keystore = args[0];
    hostname = args[1];

    String password = "changeit";
    String keyFilename =
            System.getProperty("test.src", ".") + "/" + keystore;
    String trustFilename =
            System.getProperty("test.src", ".") + "/" + keystore;

    System.setProperty("javax.net.ssl.keyStore", keyFilename);
    System.setProperty("javax.net.ssl.keyStorePassword", password);
    System.setProperty("javax.net.ssl.trustStore", trustFilename);
    System.setProperty("javax.net.ssl.trustStorePassword", password);

    context = SSLContext.getDefault();
    HttpsURLConnection.setDefaultSSLSocketFactory(
            context.getSocketFactory());
}
 
protected SSLContext generateSSLContext() {
    SSLContextBuilder contextBuilder = SSLContexts.custom();
    try {
        if (getTrustStoreFile() != null) {
            contextBuilder.loadTrustMaterial(getTrustStoreFile(), getTrustStorePassword(), getTrustStrategy());
        }

        if (getKeyStoreFile() != null) {
            contextBuilder.loadKeyMaterial(getKeyStoreFile(), getKeyStorePassword(), getKeyPassword(), getPrivateKeyStrategy());
        }

        return contextBuilder.build();
    } catch (GeneralSecurityException | IOException e) {
        throw new RuntimeException("Unable to configure SSL", e);
    }
}
 
源代码7 项目: flashback   文件: HandshakeWithClient.java
@Override
public Future execute(ChannelMediator channelMediator, InetSocketAddress remoteAddress) {

  //dynamically create SSLEngine based on CN and SANs
  LOG.debug("Starting client to proxy connection handshaking");
  try {
    //TODO: if connect request only contains ip address, we need get either CA
    //TODO: or SANS from server response
    KeyStore keyStore = _certificateKeyStoreFactory.create(remoteAddress.getHostName(), new ArrayList<>());
    SSLContext sslContext = SSLContextGenerator.createClientContext(keyStore, _certificateAuthority.getPassPhrase());
    return channelMediator.handshakeWithClient(sslContext.createSSLEngine());
  } catch (NoSuchAlgorithmException | KeyStoreException | IOException | CertificateException | OperatorCreationException
      | NoSuchProviderException | InvalidKeyException | SignatureException | KeyManagementException | UnrecoverableKeyException e) {
    throw new RuntimeException("Failed to create server identity certificate", e);
  }
}
 
@SuppressFBWarnings(value = "REC_CATCH_EXCEPTION", justification = "docker-java uses runtime exceptions")
@Override
public SSLContext getSSLContext() throws KeyManagementException, UnrecoverableKeyException,
        NoSuchAlgorithmException, KeyStoreException {
    try {
        Security.addProvider(new BouncyCastleProvider());

        SslConfigurator sslConfig = SslConfigurator.newInstance(true);
        sslConfig.securityProtocol("TLSv1.2");

        // add keystore
        sslConfig.keyStore(createKeyStore(keypem, certpem));
        sslConfig.keyStorePassword("docker"); // ??

        if (isNotBlank(capem)) {
            sslConfig.trustStore(createTrustStore(capem));
        }

        return sslConfig.createSSLContext();
    } catch (Exception e) {
        throw new DockerClientException(e.getMessage(), e);
    }
}
 
源代码9 项目: qpid-jms   文件: TransportSupportTest.java
@Test
public void testCreateSslEngineFromJksStoreWithExplicitDisabledCiphersJDK() throws Exception {
    // Discover the default enabled ciphers
    TransportOptions options = createJksSslOptions();
    SSLEngine directEngine = createSSLEngineDirectly(options);
    String[] ciphers = directEngine.getEnabledCipherSuites();
    assertTrue("There were no initial ciphers to choose from!", ciphers.length > 0);

    // Pull out one to disable specifically
    String[] disabledCipher = new String[] { ciphers[ciphers.length - 1] };
    String[] trimmedCiphers = Arrays.copyOf(ciphers, ciphers.length - 1);
    options.setDisabledCipherSuites(disabledCipher);
    SSLContext context = TransportSupport.createJdkSslContext(options);
    SSLEngine engine = TransportSupport.createJdkSslEngine(null, context, options);

    // verify the option took effect
    assertNotNull(engine);
    assertArrayEquals("Enabled ciphers not as expected", trimmedCiphers, engine.getEnabledCipherSuites());
}
 
源代码10 项目: grpc-java   文件: TestUtils.java
/**
 * Creates an SSLSocketFactory which contains {@code certChainFile} as its only root certificate.
 */
public static SSLSocketFactory newSslSocketFactoryForCa(Provider provider,
                                                        File certChainFile) throws Exception {
  KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  ks.load(null, null);
  CertificateFactory cf = CertificateFactory.getInstance("X.509");
  BufferedInputStream in = new BufferedInputStream(new FileInputStream(certChainFile));
  try {
    X509Certificate cert = (X509Certificate) cf.generateCertificate(in);
    X500Principal principal = cert.getSubjectX500Principal();
    ks.setCertificateEntry(principal.getName("RFC2253"), cert);
  } finally {
    in.close();
  }

  // Set up trust manager factory to use our key store.
  TrustManagerFactory trustManagerFactory =
      TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  trustManagerFactory.init(ks);
  SSLContext context = SSLContext.getInstance("TLS", provider);
  context.init(null, trustManagerFactory.getTrustManagers(), null);
  return context.getSocketFactory();
}
 
源代码11 项目: Burp-Hunter   文件: HunterRequest.java
public String notifyHunter(byte[] content) throws IOException {
    try {
        String request = new String(content);
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true).build();
        HttpClient httpclient = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
        HttpPost httpPost = new HttpPost("https://api"+hunterDomain.substring(hunterDomain.indexOf("."))+"/api/record_injection");
        String json = "{\"request\": \""+request.replace("\\", "\\\\").replace("\"", "\\\"").replace("\r\n", "\\n")+"\", \"owner_correlation_key\": \""+hunterKey+"\", \"injection_key\": \""+injectKey+"\"}";
        StringEntity entity = new StringEntity(json);
        entity.setContentType("applicaiton/json");
        httpPost.setEntity(entity);
        HttpResponse response = httpclient.execute(httpPost);
        String responseString = new BasicResponseHandler().handleResponse(response);
        return responseString;
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
        
        Logger.getLogger(HunterRequest.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "Error Notifying Probe Server!";
}
 
源代码12 项目: bce-sdk-java   文件: MqttConnection.java
/**
 * get SSLSocketFactory
 * @param caKeystore
 * @param clientKeystore
 * @param keystorePassword
 *
 * @return
 */
public static SSLSocketFactory getFactory(KeyStore caKeystore, KeyStore clientKeystore, String keystorePassword) {
    try {
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(caKeystore);
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(clientKeystore, keystorePassword.toCharArray());
        SSLContext context = SSLContext.getInstance(TLS_V_1_2);
        KeyManager[] kms = kmf.getKeyManagers();
        context.init(kms, tmf.getTrustManagers(), null);
        return context.getSocketFactory();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
源代码13 项目: grpc-nebula-java   文件: TestUtils.java
/**
 * Returns the ciphers preferred to use during tests. They may be chosen because they are widely
 * available or because they are fast. There is no requirement that they provide confidentiality
 * or integrity.
 *
 * @deprecated Not for public use
 */
@Deprecated
public static List<String> preferredTestCiphers() {
  String[] ciphers;
  try {
    ciphers = SSLContext.getDefault().getDefaultSSLParameters().getCipherSuites();
  } catch (NoSuchAlgorithmException ex) {
    throw new RuntimeException(ex);
  }
  List<String> ciphersMinusGcm = new ArrayList<>();
  for (String cipher : ciphers) {
    // The GCM implementation in Java is _very_ slow (~1 MB/s)
    if (cipher.contains("_GCM_")) {
      continue;
    }
    ciphersMinusGcm.add(cipher);
  }
  return Collections.unmodifiableList(ciphersMinusGcm);
}
 
源代码14 项目: grpc-nebula-java   文件: TestUtils.java
/**
 * Creates an SSLSocketFactory which contains {@code certChainFile} as its only root certificate.
 *
 * @deprecated Not for public use
 */
@Deprecated
public static SSLSocketFactory newSslSocketFactoryForCa(Provider provider,
    File certChainFile) throws Exception {
  KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  ks.load(null, null);
  CertificateFactory cf = CertificateFactory.getInstance("X.509");
  X509Certificate cert = (X509Certificate) cf.generateCertificate(
      new BufferedInputStream(new FileInputStream(certChainFile)));
  X500Principal principal = cert.getSubjectX500Principal();
  ks.setCertificateEntry(principal.getName("RFC2253"), cert);

  // Set up trust manager factory to use our key store.
  TrustManagerFactory trustManagerFactory =
      TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  trustManagerFactory.init(ks);
  SSLContext context = SSLContext.getInstance("TLS", provider);
  context.init(null, trustManagerFactory.getTrustManagers(), null);
  return context.getSocketFactory();
}
 
public SSLConfig(SSLContext sslContext, String[] supportedProtocols, String[] supportedCipherSuites,
        HostnameVerifier hostnameVerifier, boolean hostnameVerificationEnabled, boolean trustAll,
        boolean startTlsEnabled, KeyStore effectiveTruststore, List<String> effectiveTruststoreAliases,
        KeyStore effectiveKeystore, char[] effectiveKeyPassword, String effectiveKeyAlias) {
    this.sslContext = sslContext;
    this.supportedProtocols = supportedProtocols;
    this.supportedCipherSuites = supportedCipherSuites;
    this.hostnameVerifier = hostnameVerifier;
    this.hostnameVerificationEnabled = hostnameVerificationEnabled;
    this.trustAll = trustAll;
    this.startTlsEnabled = startTlsEnabled;
    this.effectiveTruststore = effectiveTruststore;
    this.effectiveTruststoreAliases = effectiveTruststoreAliases;
    this.effectiveKeystore = effectiveKeystore;
    this.effectiveKeyPassword = effectiveKeyPassword;
    this.effectiveKeyAlias = effectiveKeyAlias;

    if (log.isDebugEnabled()) {
        log.debug("Created SSLConfig: " + this);
    }
}
 
源代码16 项目: openAGV   文件: SecureSslContextFactory.java
/**
 * Creates an instance of {@link SSLContext} for the server.
 *
 * @return The ssl context.
 * @throws IllegalStateException If the creation of the ssl context fails.
 */
public SSLContext createServerContext()
    throws IllegalStateException {
  SSLContext context = null;

  try {
    KeyStore ks = KeyStore.getInstance(sslParameterSet.getKeystoreType());
    ks.load(new FileInputStream(sslParameterSet.getKeystoreFile()),
            sslParameterSet.getKeystorePassword().toCharArray());
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KEY_TRUST_MANAGEMENT_ALGORITHM);
    kmf.init(ks, sslParameterSet.getKeystorePassword().toCharArray());

    context = SSLContext.getInstance(SSL_CONTEXT_PROTOCOL);
    context.init(kmf.getKeyManagers(), null, null);

  }
  catch (NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException
             | KeyManagementException | UnrecoverableKeyException ex) {
    throw new IllegalStateException("Error creating the server's ssl context", ex);
  }

  return context;
}
 
源代码17 项目: nifi-registry   文件: IntegrationTestBase.java
private static Client createClientFromConfig(NiFiRegistryClientConfig registryClientConfig) {

        final ClientConfig clientConfig = new ClientConfig();
        clientConfig.register(jacksonJaxbJsonProvider());

        final ClientBuilder clientBuilder = ClientBuilder.newBuilder().withConfig(clientConfig);

        final SSLContext sslContext = registryClientConfig.getSslContext();
        if (sslContext != null) {
            clientBuilder.sslContext(sslContext);
        }

        final HostnameVerifier hostnameVerifier = registryClientConfig.getHostnameVerifier();
        if (hostnameVerifier != null) {
            clientBuilder.hostnameVerifier(hostnameVerifier);
        }

        return clientBuilder.build();
    }
 
源代码18 项目: ranger   文件: DefaultSchemaRegistryClient.java
public DefaultSchemaRegistryClient(Map<String, ?> conf) {
    configuration = new Configuration(conf);
    login = SecurityUtils.initializeSecurityContext(conf);
    ClientConfig config = createClientConfig(conf);
    final boolean SSLEnabled = SecurityUtils.isHttpsConnection(conf);
    ClientBuilder clientBuilder = JerseyClientBuilder.newBuilder()
            .withConfig(config)
            .property(ClientProperties.FOLLOW_REDIRECTS, Boolean.TRUE);
    if (SSLEnabled) {
        SSLContext ctx;
        try {
            ctx = SecurityUtils.createSSLContext(conf, SSL_ALGORITHM);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        clientBuilder.sslContext(ctx);
    }
    client = clientBuilder.build();

    // get list of urls and create given or default UrlSelector.
    urlSelector = createUrlSelector();
    urlWithTargets = new ConcurrentHashMap<>();
}
 
@Bean
    @Primary
    @Autowired
    public HttpClient httpClientWithOutProxy(TrustManager[] trustAllCertificates, ExecutorService httpclientExecutorService) throws NoSuchAlgorithmException, KeyManagementException {
        SSLParameters sslParams = new SSLParameters();
        sslParams.setEndpointIdentificationAlgorithm("");
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCertificates, new SecureRandom());
        return HttpClient.newBuilder()
                .version(HttpClient.Version.HTTP_1_1)
//                .sslParameters(sslParams)
//                .sslContext(sc)
                .connectTimeout(Duration.ofSeconds(30))
              //          .proxy(ProxySelector.of(new InetSocketAddress("127.0.0.1", 8888)))
                .executor(httpclientExecutorService)
                .followRedirects(HttpClient.Redirect.NEVER)
                .build();
    }
 
源代码20 项目: nexus-public   文件: TrustStoreImpl.java
@Override
public SSLContext getSSLContext() {
  SSLContext _sslcontext = this.sslcontext; // local variable allows concurrent removeTrustCertificate
  if (_sslcontext == null) {
    try {
      // the trusted key store may have asychronously changed when NXRM is clustered, reload the managed store used
      // for fallback so the context doesn't use stale key store
      this.managedTrustManager = getManagedTrustManager(keyStoreManager);
      _sslcontext = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
      _sslcontext.init(keyManagers, trustManagers, DEFAULT_RANDOM);
      this.sslcontext = _sslcontext;
    }
    catch (Exception e) {
      log.debug("Could not create SSL context", e);
      Throwables.throwIfUnchecked(e);
      throw new RuntimeException(e);
    }
  }
  return _sslcontext;
}
 
源代码21 项目: datakernel   文件: AsyncTcpSocketSslTest.java
static SSLContext createSslContext() throws Exception {
	SSLContext instance = SSLContext.getInstance("TLSv1.2");

	KeyStore keyStore = KeyStore.getInstance("JKS");
	KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	try (InputStream input = new FileInputStream(new File(KEYSTORE_PATH))) {
		keyStore.load(input, KEYSTORE_PASS.toCharArray());
	}
	kmf.init(keyStore, KEY_PASS.toCharArray());

	KeyStore trustStore = KeyStore.getInstance("JKS");
	TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
	try (InputStream input = new FileInputStream(new File(TRUSTSTORE_PATH))) {
		trustStore.load(input, TRUSTSTORE_PASS.toCharArray());
	}
	tmf.init(trustStore);

	instance.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
	return instance;
}
 
源代码22 项目: Bats   文件: SSLConfigClient.java
@Override
public SSLContext initJDKSSLContext() throws DrillException {
  final SSLContext sslCtx;

  if (!userSslEnabled) {
    return null;
  }

  TrustManagerFactory tmf;
  try {
    tmf = initializeTrustManagerFactory();
    sslCtx = SSLContext.getInstance(protocol);
    sslCtx.init(null, tmf.getTrustManagers(), null);
  } catch (Exception e) {
    // Catch any SSL initialization Exceptions here and abort.
    throw new DrillException(new StringBuilder()
        .append("SSL is enabled but cannot be initialized due to the following exception: ")
        .append("[ ")
        .append(e.getMessage())
        .append("]. ")
        .toString());
  }
  this.jdkSSlContext = sslCtx;
  return sslCtx;
}
 
源代码23 项目: mt-flume   文件: AvroSource.java
private SSLContext createServerSSLContext() {
  try {
    KeyStore ks = KeyStore.getInstance(keystoreType);
    ks.load(new FileInputStream(keystore), keystorePassword.toCharArray());

    // Set up key manager factory to use our key store
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(getAlgorithm());
    kmf.init(ks, keystorePassword.toCharArray());

    SSLContext serverContext = SSLContext.getInstance("TLS");
    serverContext.init(kmf.getKeyManagers(), null, null);
    return serverContext;
  } catch (Exception e) {
    throw new Error("Failed to initialize the server-side SSLContext", e);
  }
}
 
源代码24 项目: webdsl   文件: URLType.java
protected static void setAcceptAllVerifier(HttpsURLConnection connection) throws NoSuchAlgorithmException, KeyManagementException {

        // Create the socket factory.
        // Reusing the same socket factory allows sockets to be
        // reused, supporting persistent connections.
        if( null == sslSocketFactory) {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, ALL_TRUSTING_TRUST_MANAGER, new java.security.SecureRandom());
            sslSocketFactory = sc.getSocketFactory();
        }

        connection.setSSLSocketFactory(sslSocketFactory);

        // Since we may be using a cert with a different name, we need to ignore
        // the hostname as well.
        connection.setHostnameVerifier(ALL_TRUSTING_HOSTNAME_VERIFIER);
    }
 
/**
 * Constructor for a secure ChannelIO variant.
 */
public SslReadWriteSelectorHandler(SocketChannel sc, SelectionKey selectionKey,
                                   SSLContext sslContext) throws IOException {
    super(sc);

    sslEngine = sslContext.createSSLEngine();
    sslEngine.setUseClientMode(false);
    initialHSStatus = HandshakeStatus.NEED_UNWRAP;
    initialHSComplete = false;

    int netBBSize = sslEngine.getSession().getPacketBufferSize();
    inNetBB = ByteBuffer.allocate(netBBSize);
    outNetBB = ByteBuffer.allocate(netBBSize);
    outNetBB.position(0);
    outNetBB.limit(0);

    int appBBSize = sslEngine.getSession().getApplicationBufferSize();
    requestBB = ByteBuffer.allocate(appBBSize);

    while (!doHandshake(selectionKey)) {

    }
}
 
源代码26 项目: braintree_android   文件: TLSSocketFactory.java
/**
 * @see <a href="http://developer.android.com/training/articles/security-ssl.html#UnknownCa">Android Documentation</a>
 */
public TLSSocketFactory(InputStream certificateStream) throws SSLException {
    try {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);

        CertificateFactory cf = CertificateFactory.getInstance("X.509");

        Collection<? extends Certificate> certificates =
                cf.generateCertificates(certificateStream);
        for (Certificate cert : certificates) {
            if (cert instanceof X509Certificate) {
                String subject = ((X509Certificate) cert).getSubjectDN().getName();
                keyStore.setCertificateEntry(subject, cert);
            }
        }

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(
                TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keyStore);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tmf.getTrustManagers(), null);
        mInternalSSLSocketFactory = sslContext.getSocketFactory();
    } catch (Exception e) {
        throw new SSLException(e.getMessage());
    } finally {
        try {
            certificateStream.close();
        } catch (IOException | NullPointerException ignored) {}
    }
}
 
源代码27 项目: nats.java   文件: OptionsTests.java
@Test
public void testConnectOptionsWithNameAndContext() throws Exception {
    SSLContext ctx = TestSSLUtils.createTestSSLContext();
    Options o = new Options.Builder().sslContext(ctx).connectionName("c1").build();
    String expected = "{\"lang\":\"java\",\"version\":\"" + Nats.CLIENT_VERSION + "\",\"name\":\"c1\""
            + ",\"protocol\":1,\"verbose\":false,\"pedantic\":false,\"tls_required\":true,\"echo\":true}";
    assertEquals("default connect options", expected, o.buildProtocolConnectOptionsString("nats://localhost:4222", false, null).toString());
}
 
源代码28 项目: localization_nifi   文件: SetCacheServer.java
public SetCacheServer(final String identifier, final SSLContext sslContext, final int port, final int maxSize,
        final EvictionPolicy evictionPolicy, final File persistencePath) throws IOException {
    super(identifier, sslContext, port);

    final SetCache simpleCache = new SimpleSetCache(identifier, maxSize, evictionPolicy);

    if (persistencePath == null) {
        this.cache = simpleCache;
    } else {
        final PersistentSetCache persistentCache = new PersistentSetCache(identifier, persistencePath, simpleCache);
        persistentCache.restore();
        this.cache = persistentCache;
    }
}
 
源代码29 项目: jdk8u_jdk   文件: UnboundSSLUtils.java
static SSLClient init(String host, int port, String cipherSuiteFilter,
        String sniHostName) throws NoSuchAlgorithmException, IOException {
    SSLContext sslContext = SSLContext.getDefault();
    SSLSocketFactory ssf = (SSLSocketFactory) sslContext.getSocketFactory();
    SSLSocket socket = (SSLSocket) ssf.createSocket(host, port);
    SSLParameters params = new SSLParameters();

    if (cipherSuiteFilter != null) {
        String[] cipherSuites = UnboundSSLUtils.filterStringArray(
                ssf.getSupportedCipherSuites(), cipherSuiteFilter);
        System.out.println("Client: enabled cipher suites: "
                + Arrays.toString(cipherSuites));
        params.setCipherSuites(cipherSuites);
    }

    if (sniHostName != null) {
        System.out.println("Client: set SNI hostname: " + sniHostName);
        SNIHostName serverName = new SNIHostName(sniHostName);
        List<SNIServerName> serverNames = new ArrayList<>();
        serverNames.add(serverName);
        params.setServerNames(serverNames);
    }

    socket.setSSLParameters(params);

    return new SSLClient(socket);
}
 
@Override
public SSLContext sslContext() {
    try {
        return SSLContextLoader.getInitialisedContext();
    } catch (NoSuchAlgorithmException | KeyStoreException | CertificateException |
            IOException | KeyManagementException | UnrecoverableKeyException e) {
        throw new RuntimeException("Failed to load ssl context", e);
    }
}
 
 类所在包