类org.apache.http.ssl.PrivateKeyStrategy源码实例Demo

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

源代码1 项目: apiman   文件: SSLSessionStrategyFactory.java
private static SSLContextBuilder loadKeyMaterial(SSLContextBuilder builder, File file, char[] ksp,
        char[] kp, PrivateKeyStrategy privateKeyStrategy) throws NoSuchAlgorithmException,
                KeyStoreException, UnrecoverableKeyException, CertificateException, IOException {
    Args.notNull(file, "Keystore file"); //$NON-NLS-1$
    final KeyStore identityStore = KeyStore.getInstance(KeyStore.getDefaultType());
    final FileInputStream instream = new FileInputStream(file);
    try {
        identityStore.load(instream, ksp);
    } finally {
        instream.close();
    }
    return builder.loadKeyMaterial(identityStore, kp, privateKeyStrategy);
}
 
private void configureWithSettings() throws SSLConfigException, NoSuchAlgorithmException, KeyStoreException {
    this.enabled = getSettingAsBoolean(ENABLE_SSL, false);

    if (!this.enabled) {
        return;
    }

    this.enableSslClientAuth = getSettingAsBoolean(ENABLE_SSL_CLIENT_AUTH, false);

    if (settings.get(settingsKeyPrefix + PEMTRUSTEDCAS_FILEPATH, null) != null
            || settings.get(settingsKeyPrefix + PEMTRUSTEDCAS_CONTENT, null) != null) {
        initFromPem();
    } else {
        initFromKeyStore();
    }

    if (effectiveTruststore != null) {
        sslContextBuilder.loadTrustMaterial(effectiveTruststore, null);
    }

    if (enableSslClientAuth) {
        if (effectiveKeystore != null) {
            try {
                sslContextBuilder.loadKeyMaterial(effectiveKeystore, effectiveKeyPassword,
                        new PrivateKeyStrategy() {

                            @Override
                            public String chooseAlias(Map<String, PrivateKeyDetails> aliases, Socket socket) {
                                if (aliases == null || aliases.isEmpty()) {
                                    return effectiveKeyAlias;
                                }

                                if (effectiveKeyAlias == null || effectiveKeyAlias.isEmpty()) {
                                    return aliases.keySet().iterator().next();
                                }

                                return effectiveKeyAlias;
                            }
                        });
            } catch (UnrecoverableKeyException e) {
                throw new RuntimeException(e);
            }
        }
    }

}
 
private final HttpAsyncClientBuilder asyncClientBuilder(HttpAsyncClientBuilder httpClientBuilder)
        throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {

    // basic auth
    // pki auth

    if (ssl) {

        final SSLContextBuilder sslContextBuilder = SSLContexts.custom();

        if (log.isTraceEnabled()) {
            log.trace("Configure HTTP client with SSL");
        }

        if (trustStore != null) {
            sslContextBuilder.loadTrustMaterial(trustStore, null);
        }

        if (keystore != null) {
            sslContextBuilder.loadKeyMaterial(keystore, keyPassword, new PrivateKeyStrategy() {

                @Override
                public String chooseAlias(Map<String, PrivateKeyDetails> aliases, Socket socket) {
                    if(aliases == null || aliases.isEmpty()) {
                        return keystoreAlias;
                    }

                    if(keystoreAlias == null || keystoreAlias.isEmpty()) {
                        return aliases.keySet().iterator().next();
                    }

                    return keystoreAlias;                    }
            });
        }

        final HostnameVerifier hnv = verifyHostnames?new DefaultHostnameVerifier():NoopHostnameVerifier.INSTANCE;

        final SSLContext sslContext = sslContextBuilder.build();
        httpClientBuilder.setSSLStrategy(new SSLIOSessionStrategy(
                sslContext,
                supportedProtocols,
                supportedCipherSuites,
                hnv
                ));
    }

    if (basicCredentials != null) {
        httpClientBuilder.setDefaultHeaders(Lists.newArrayList(new BasicHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicCredentials)));
    }

    // TODO: set a timeout until we have a proper way to deal with back pressure
    int timeout = 5;

    RequestConfig config = RequestConfig.custom()
      .setConnectTimeout(timeout * 1000)
      .setConnectionRequestTimeout(timeout * 1000)
      .setSocketTimeout(timeout * 1000).build();

    httpClientBuilder.setDefaultRequestConfig(config);

    return httpClientBuilder;

}
 
@Test
public void clientCertTest() throws Exception {

    try (MockIpdServer sslMockIdpServer = new MockIpdServer(TestJwk.Jwks.ALL, SocketUtils.findAvailableTcpPort(),
            true) {
        @Override
        protected void handleDiscoverRequest(HttpRequest request, HttpResponse response, HttpContext context)
                throws HttpException, IOException {

            MockIpdServer.SSLTestHttpServerConnection connection = (MockIpdServer.SSLTestHttpServerConnection) ((HttpCoreContext) context)
                    .getConnection();

            X509Certificate peerCert = (X509Certificate) connection.getPeerCertificates()[0];

            try {
                String sha256Fingerprint = Hashing.sha256().hashBytes(peerCert.getEncoded()).toString();

                Assert.assertEquals("04b2b8baea7a0a893f0223d95b72081e9a1e154a0f9b1b4e75998085972b1b68",
                        sha256Fingerprint);

            } catch (CertificateEncodingException e) {
                throw new RuntimeException(e);
            }

            super.handleDiscoverRequest(request, response, context);
        }
    }) {
        SSLContextBuilder sslContextBuilder = SSLContexts.custom();

        KeyStore trustStore = KeyStore.getInstance("JKS");
        InputStream trustStream = new FileInputStream(
                FileHelper.getAbsoluteFilePathFromClassPath("jwt/truststore.jks").toFile());
        trustStore.load(trustStream, "changeit".toCharArray());

        KeyStore keyStore = KeyStore.getInstance("JKS");
        InputStream keyStream = new FileInputStream(
                FileHelper.getAbsoluteFilePathFromClassPath("jwt/spock-keystore.jks").toFile());

        keyStore.load(keyStream, "changeit".toCharArray());

        sslContextBuilder.loadTrustMaterial(trustStore, null);

        sslContextBuilder.loadKeyMaterial(keyStore, "changeit".toCharArray(), new PrivateKeyStrategy() {

            @Override
            public String chooseAlias(Map<String, PrivateKeyDetails> aliases, Socket socket) {
                return "spock";
            }
        });

        SettingsBasedSSLConfigurator.SSLConfig sslConfig = new SettingsBasedSSLConfigurator.SSLConfig(
                sslContextBuilder.build(), new String[] { "TLSv1.2", "TLSv1.1" }, null, null, false, false, false,
                trustStore, null, keyStore, null, null);

        KeySetRetriever keySetRetriever = new KeySetRetriever(sslMockIdpServer.getDiscoverUri(), sslConfig, false);

        keySetRetriever.get();

    }
}
 
private SSLContext createSSLContext(String trustStorePath, String keyStorePath, String password) {

            try {
                TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                KeyStore trustStore = KeyStore.getInstance("JKS");
                InputStream trustStream = new FileInputStream(
                        FileHelper.getAbsoluteFilePathFromClassPath(trustStorePath).toFile());
                trustStore.load(trustStream, password.toCharArray());
                tmf.init(trustStore);

                KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                KeyStore keyStore = KeyStore.getInstance("JKS");

                Path path = FileHelper.getAbsoluteFilePathFromClassPath(keyStorePath);

                if (path == null) {
                    throw new RuntimeException("Could not find " + keyStorePath);
                }

                InputStream keyStream = new FileInputStream(path.toFile());

                keyStore.load(keyStream, password.toCharArray());
                kmf.init(keyStore, password.toCharArray());

                SSLContextBuilder sslContextBuilder = SSLContexts.custom();

                sslContextBuilder.loadTrustMaterial(trustStore, null);

                sslContextBuilder.loadKeyMaterial(keyStore, password.toCharArray(), new PrivateKeyStrategy() {

                    @Override
                    public String chooseAlias(Map<String, PrivateKeyDetails> aliases, Socket socket) {
                        return "node1";
                    }
                });

                return sslContextBuilder.build();
            } catch (GeneralSecurityException | IOException e) {
                throw new RuntimeException(e);
            }
        }
 
public PrivateKeyStrategy getPrivateKeyStrategy() {
    return keyStrategy;
}
 
public void setPrivateKeyStrategy(PrivateKeyStrategy keyStrategy) {
    this.keyStrategy = keyStrategy;
}
 
源代码8 项目: apiman   文件: SSLSessionStrategyFactory.java
/**
 * Build an {@link SSLSessionStrategy}.
 *
 * @param trustStore the trust store
 * @param trustStorePassword the truststore password (if any)
 * @param keyStore the keystore
 * @param keyStorePassword the keystore password (if any)
 * @param keyAliases the key aliases that are candidates for use (if any)
 * @param keyPassword the key password (if any)
 * @param allowedProtocols the allowed transport protocols.
 *            <strong><em>Avoid specifying insecure protocols</em></strong>
 * @param allowedCiphers allowed crypto ciphersuites, <tt>null</tt> to use system defaults
 * @param trustSelfSigned true if self signed certificates can be trusted.
 *             <strong><em>Use with caution</em></strong>
 * @param allowAnyHostname true if any hostname can be connected to (i.e. does not need to match
 *            certificate hostname). <strong><em>Do not use in production</em></strong>
 * @return the connection socket factory
 * @throws NoSuchAlgorithmException if the selected algorithm is not available on the system
 * @throws KeyStoreException if there was a problem with the keystore
 * @throws CertificateException if there was a problem with the certificate
 * @throws IOException if the truststore could not be found or was invalid
 * @throws KeyManagementException if there is a problem with keys
 * @throws UnrecoverableKeyException if the key cannot be recovered
 */
public static SSLSessionStrategy build(String trustStore,
        String trustStorePassword,
        String keyStore,
        String keyStorePassword,
        String[] keyAliases,
        String keyPassword,
        String[] allowedProtocols,
        String[] allowedCiphers,
        boolean allowAnyHostname,
        boolean trustSelfSigned)

throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException,
        KeyManagementException, UnrecoverableKeyException {

    Args.notNull(allowedProtocols, "Allowed protocols"); //$NON-NLS-1$
    Args.notNull(allowedCiphers, "Allowed ciphers"); //$NON-NLS-1$

    TrustStrategy trustStrategy = trustSelfSigned ?  SELF_SIGNED : null;
    HostnameVerifier hostnameVerifier = allowAnyHostname ? ALLOW_ANY :
        SSLConnectionSocketFactory.getDefaultHostnameVerifier();
    PrivateKeyStrategy privateKeyStrategy = keyAliases == null ? null : new SelectByAlias(keyAliases);
    boolean clientAuth = keyStore == null ? false : true;

    SSLContextBuilder builder = SSLContexts.custom();

    if (trustStore != null) {
        loadTrustMaterial(builder,
                new File(trustStore),
                trustStorePassword.toCharArray(),
                trustStrategy);
    }

    if (keyStore != null) {
        char[] ksp = keyStorePassword == null ? null : keyStorePassword.toCharArray();
        char[] kp = keyPassword == null ? null : keyPassword.toCharArray();
        loadKeyMaterial(builder, new File(keyStore), ksp, kp, privateKeyStrategy);
    }

    SSLContext sslContext = builder.build();
    return new SSLSessionStrategy(hostnameVerifier, new CipherSelectingSSLSocketFactory(
            sslContext.getSocketFactory(), allowedCiphers, allowedProtocols, clientAuth));
}
 
 类所在包
 同包方法