javax.net.ssl.KeyManagerFactory Java Examples

The following examples show how to use javax.net.ssl.KeyManagerFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TesterSupport.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
protected static KeyManager[] getUser1KeyManagers() throws Exception {
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(
            KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(getKeyStore(CLIENT_JKS), JKS_PASS.toCharArray());
    KeyManager[] managers = kmf.getKeyManagers();
    KeyManager manager;
    for (int i=0; i < managers.length; i++) {
        manager = managers[i];
        if (manager instanceof X509ExtendedKeyManager) {
            managers[i] = new TrackingExtendedKeyManager((X509ExtendedKeyManager)manager);
        } else if (manager instanceof X509KeyManager) {
            managers[i] = new TrackingKeyManager((X509KeyManager)manager);
        }
    }
    return managers;
}
 
Example #2
Source File: Link.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #3
Source File: TestTLS12.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
static private SSLEngine createSSLEngine(boolean client)
        throws Exception {
    SSLEngine ssle;
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX",
            jsseProvider);
    kmf.init(ks, passphrase);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX",
            jsseProvider);
    tmf.init(ts);

    SSLContext sslCtx = SSLContext.getInstance("TLSv1.2",
            jsseProvider);
    sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    ssle = sslCtx.createSSLEngine("localhost", 443);
    ssle.setUseClientMode(client);
    SSLParameters sslParameters = ssle.getSSLParameters();
    ssle.setSSLParameters(sslParameters);

    return ssle;
}
 
Example #4
Source File: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
void loadSigningKeys(String path, String alias) {
    try {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());

        KeyStore keyStore = KeyStore.getInstance("JKS");
        InputStream keyStream = new FileInputStream(FileHelper.getAbsoluteFilePathFromClassPath(path).toFile());

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

        this.signingCertificate = (X509Certificate) keyStore.getCertificate(alias);

        this.signingCredential = new BasicX509Credential(this.signingCertificate,
                (PrivateKey) keyStore.getKey(alias, "changeit".toCharArray()));

    } catch (NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException
            | UnrecoverableKeyException e) {
        throw new RuntimeException(e);
    }
}
 
Example #5
Source File: BridgeServerTlsContextImpl.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
private static KeyManagerFactory createKeyManagerFactory(BridgeServerConfig serverConfig)
   throws IOException, KeyStoreException, CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException {
   String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
   if (algorithm == null) {
      algorithm = "SunX509";
   }

   KeyStore ks = KeyStoreLoader.loadKeyStore(
      serverConfig.getTlsServerKeystoreFilepath(),
      serverConfig.getTlsServerKeystorePassword()
   );

   KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
   kmf.init(ks, serverConfig.getTlsServerKeyPassword().toCharArray());

   return kmf;
}
 
Example #6
Source File: NettyTransport.java    From jzab with Apache License 2.0 6 votes vote down vote up
private void initSsl() throws IOException, GeneralSecurityException {
  String kmAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
  String tmAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
  // TODO make the protocol and keystore type configurable.
  String protocol = "TLS";
  KeyStore ks = KeyStore.getInstance("JKS");
  KeyStore ts = KeyStore.getInstance("JKS");
  try (FileInputStream keyStoreStream = new FileInputStream(keyStore);
       FileInputStream trustStoreStream = new FileInputStream(trustStore)) {
    ks.load(keyStoreStream, keyStorePassword);
    ts.load(trustStoreStream, trustStorePassword);
  }
  KeyManagerFactory kmf = KeyManagerFactory.getInstance(kmAlgorithm);
  TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm);
  kmf.init(ks, keyStorePassword);
  tmf.init(ts);
  serverContext = SSLContext.getInstance(protocol);
  clientContext = SSLContext.getInstance(protocol);
  serverContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
  clientContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
}
 
Example #7
Source File: AvroSource.java    From mt-flume with Apache License 2.0 6 votes vote down vote up
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);
  }
}
 
Example #8
Source File: HSSLSocketFactory.java    From appcan-android with GNU Lesser General Public License v3.0 6 votes vote down vote up
public HSSLSocketFactory(KeyStore ksP12, String keyPass) throws Exception {
    super(ksP12);
    mSSLContext = SSLContext.getInstance(SSLSocketFactory.TLS);
    KeyManagerFactory kMgrFact = null;
    TrustManager[] tMgrs = null;
    KeyManager[] kMgrs = null;
    TrustManager tMgr = null;
    tMgr = new HX509TrustManager(ksP12);
    kMgrFact = KeyManagerFactory.getInstance(Http.algorithm);
    if (null != keyPass) {
        kMgrFact.init(ksP12, keyPass.toCharArray());
    } else {
        kMgrFact.init(ksP12, null);
    }
    kMgrs = kMgrFact.getKeyManagers();
    tMgrs = new TrustManager[]{tMgr};
    SecureRandom secureRandom = new java.security.SecureRandom();
    mSSLContext.init(kMgrs, tMgrs, secureRandom);
    if (!Http.isCheckTrustCert()) {
        setHostnameVerifier(new HX509HostnameVerifier());
    } else {
        setHostnameVerifier(STRICT_HOSTNAME_VERIFIER);
    }
}
 
Example #9
Source File: ApacheThriftMethodInvokerFactory.java    From drift with Apache License 2.0 6 votes vote down vote up
private static SSLContext createSslContext(ApacheThriftClientConfig config)
{
    try {
        KeyStore trustStore = PemReader.loadTrustStore(config.getTrustCertificate());
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        KeyManager[] keyManagers = null;
        if (config.getKey() != null) {
            Optional<String> keyPassword = Optional.ofNullable(config.getKeyPassword());
            KeyStore keyStore = PemReader.loadKeyStore(config.getTrustCertificate(), config.getKey(), keyPassword);
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, new char[0]);
            keyManagers = keyManagerFactory.getKeyManagers();
        }

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagers, trustManagerFactory.getTrustManagers(), null);
        return sslContext;
    }
    catch (IOException | GeneralSecurityException e) {
        throw new IllegalArgumentException("Unable to load SSL keys", e);
    }
}
 
Example #10
Source File: Server.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Creates and returns an SSLContext by reading information from a keystore. <br>
 * Change the hardcoded options to match your configuration and your environment.
 */
private static SSLContext createSSLContext() throws Exception
{
   String keystoreName = "key.store";
   String keystorePassword = "storepwd";

   KeyStore keystore = KeyStore.getInstance("JKS");
   InputStream keystoreStream = Server.class.getClassLoader().getResourceAsStream(keystoreName);
   // Must check for nullity, otherwise a new empty keystore is created by KeyStore.load
   if (keystoreStream == null) throw new IOException("Cannot find KeyStore " + keystoreName + " in classpath");
   keystore.load(keystoreStream, keystorePassword.toCharArray());

   KeyManagerFactory keyFactory = KeyManagerFactory.getInstance("SunX509");
   keyFactory.init(keystore, keystorePassword.toCharArray());

   SSLContext context = SSLContext.getInstance("TLS");
   context.init(keyFactory.getKeyManagers(), null, null);

   return context;
}
 
Example #11
Source File: SSLUtils.java    From beam with Apache License 2.0 6 votes vote down vote up
/**
 * register ssl contects to accept all issue certificates.
 *
 * @return SSLContext
 */
static SSLContext ignoreSSLCertificate() {
  try {
    // Install the all-trusting trust manager
    SSLContext sc = SSLContext.getInstance("TLS");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(
        SSLUtils.class.getClassLoader().getResourceAsStream("resources/.keystore"),
        "changeit".toCharArray());
    KeyManagerFactory kmf =
        KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, "changeit".toCharArray());
    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(kmf.getKeyManagers(), trustAllCerts, null);
    SSLContext.setDefault(ctx);
    return ctx;
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example #12
Source File: SslHandlerFactory.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #13
Source File: HttpWebConnectionInsecureSSLWithClientCertificateTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Before
public void setUp() throws Exception {
    final URL url = getClass().getClassLoader().getResource("insecureSSL.keystore");
    final KeyStore keystore = KeyStore.getInstance("jks");
    final char[] pwd = "nopassword".toCharArray();
    keystore.load(url.openStream(), pwd);

    final TrustManagerFactory trustManagerFactory = createTrustManagerFactory();
    trustManagerFactory.init(keystore);
    final TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

    final KeyManagerFactory keyManagerFactory = createKeyManagerFactory();
    keyManagerFactory.init(keystore, pwd);
    final KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

    final SSLContext serverSSLContext = SSLContext.getInstance("TLS");
    serverSSLContext.init(keyManagers, trustManagers, null);

    localServer_ = new LocalTestServer(serverSSLContext);
    localServer_.start();
}
 
Example #14
Source File: SSLManager.java    From peer-os with Apache License 2.0 6 votes vote down vote up
public KeyManager[] getClientKeyManagers()
{

    KeyManager[] keyManagers = null;
    KeyManagerFactory keyManagerFactory;

    try
    {
        keyManagerFactory = KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm() );
        keyManagerFactory.init( keyStore, keyStoreData.getPassword().toCharArray() );
        keyManagers = keyManagerFactory.getKeyManagers();
    }
    catch ( Exception e )
    {
        LOGGER.error( "Error getting array of client key managers: {}", e.getMessage() );
    }

    return keyManagers;
}
 
Example #15
Source File: CqlCount.java    From cassandra-count with Apache License 2.0 6 votes vote down vote up
private SSLOptions createSSLOptions()
     throws KeyStoreException, FileNotFoundException, IOException, NoSuchAlgorithmException,
            KeyManagementException, CertificateException, UnrecoverableKeyException {
     TrustManagerFactory tmf = null;
     KeyStore tks = KeyStore.getInstance("JKS");
     tks.load((InputStream) new FileInputStream(new File(truststorePath)),
truststorePwd.toCharArray());
     tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
     tmf.init(tks);

     KeyManagerFactory kmf = null;
     if (null != keystorePath) {
         KeyStore kks = KeyStore.getInstance("JKS");
         kks.load((InputStream) new FileInputStream(new File(keystorePath)),
    keystorePwd.toCharArray());
         kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
         kmf.init(kks, keystorePwd.toCharArray());
     }

     SSLContext sslContext = SSLContext.getInstance("TLS");
     sslContext.init(kmf != null? kmf.getKeyManagers() : null,
                     tmf != null ? tmf.getTrustManagers() : null,
                     new SecureRandom());

     return JdkSSLOptions.builder().withSSLContext(sslContext).build(); //SSLOptions.DEFAULT_SSL_CIPHER_SUITES);
 }
 
Example #16
Source File: HttpServletProtocolSpringAdapter.java    From spring-boot-protocol with Apache License 2.0 6 votes vote down vote up
/**
 * Get the key manager
 * @param ssl ssl
 * @param sslStoreProvider sslStoreProvider
 * @return KeyManagerFactory
 * @throws Exception Exception
 */
protected KeyManagerFactory getKeyManagerFactory(Ssl ssl,SslStoreProvider sslStoreProvider) throws Exception {
    KeyStore keyStore;
    if (sslStoreProvider != null) {
        keyStore = sslStoreProvider.getKeyStore();
    }else {
        keyStore = loadKeyStore(ssl.getKeyStoreType(), ssl.getKeyStoreProvider(),ssl.getKeyStore(), ssl.getKeyStorePassword());
    }

    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    char[] keyPassword = (ssl.getKeyPassword() != null) ? ssl.getKeyPassword().toCharArray() : null;
    if (keyPassword == null && ssl.getKeyStorePassword() != null) {
        keyPassword = ssl.getKeyStorePassword().toCharArray();
    }
    keyManagerFactory.init(keyStore, keyPassword);
    return keyManagerFactory;
}
 
Example #17
Source File: SSLEngineFactory.java    From java-dcp-client with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new {@link SSLEngine} constructed from the config settings.
 *
 * @return a {@link SSLEngine} ready to be used.
 */
public SSLEngine get() {
  try {
    String pass = env.sslKeystorePassword();
    char[] password = pass == null || pass.isEmpty() ? null : pass.toCharArray();

    KeyStore ks = env.sslKeystore();
    if (ks == null) {
      ks = KeyStore.getInstance(KeyStore.getDefaultType());
      String ksFile = env.sslKeystoreFile();
      if (ksFile == null || ksFile.isEmpty()) {
        throw new IllegalArgumentException("Path to Keystore File must not be null or empty.");
      }
      ks.load(new FileInputStream(ksFile), password);
    }
    String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(defaultAlgorithm);
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(defaultAlgorithm);
    kmf.init(ks, password);
    tmf.init(ks);

    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    SSLEngine engine = ctx.createSSLEngine();
    engine.setUseClientMode(true);
    return engine;
  } catch (Exception ex) {
    throw new SSLException("Could not create SSLEngine.", ex);
  }
}
 
Example #18
Source File: MqttSslContextCreator.java    From spring-boot-protocol with Apache License 2.0 5 votes vote down vote up
private SslContextBuilder builderWithJdkProvider(KeyStore ks, String keyPassword)
        throws GeneralSecurityException {
    logger.info("Initializing key manager...");
    final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, keyPassword.toCharArray());
    logger.info("Initializing SSL context...");
    return SslContextBuilder.forServer(kmf);
}
 
Example #19
Source File: SSLKeyManager.java    From PADListener with GNU General Public License v2.0 5 votes vote down vote up
public synchronized void addKeyStore(String description, KeyStore ks, char[] password) throws KeyStoreException, UnrecoverableKeyException {
    try {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, password);
        KeyManager km = kmf.getKeyManagers()[0];
        if (!(km instanceof X509KeyManager))
            throw new KeyStoreException("KeyManager for " + description + "is not X509!");
        _stores.put(description, ks);
        _managers.put(description, (X509KeyManager) km);
    } catch (NoSuchAlgorithmException nsae) {
        _logger.severe("This should never happen! SunX509 algorithm not found: " + nsae.getMessage());
    }
    _changeSupport.firePropertyChange(KEY_PROPERTY, null, null);
}
 
Example #20
Source File: GeoLocationProviderServiceImpl.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes the SSL Context
 */
private SSLContext initSSLConnection(String tenantAdminUser)
        throws NoSuchAlgorithmException, UnrecoverableKeyException,
               KeyStoreException, KeyManagementException, IOException, CertificateException {
    String keyStorePassword = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Password");
    String trustStorePassword = ServerConfiguration.getInstance().getFirstProperty(
            "Security.TrustStore.Password");
    String keyStoreLocation = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Location");
    String trustStoreLocation = ServerConfiguration.getInstance().getFirstProperty(
            "Security.TrustStore.Location");

    //Call to load the keystore.
    KeyStore keyStore = loadKeyStore(keyStoreLocation, keyStorePassword.toCharArray());
    //Call to load the TrustStore.
    KeyStore trustStore = loadTrustStore(trustStoreLocation, trustStorePassword.toCharArray());

    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KEY_MANAGER_TYPE);
    keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TRUST_MANAGER_TYPE);
    trustManagerFactory.init(trustStore);

    // Create and initialize SSLContext for HTTPS communication

    SSLContext sslContext = SSLContext.getInstance(SSLV3);
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
    SSLContext.setDefault(sslContext);
    return sslContext;
}
 
Example #21
Source File: KeyStoreConfiguration.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
public KeyManagerFactory initKeyManagerFactory() throws NoSuchAlgorithmException, UnrecoverableKeyException,
        KeyStoreException {
    final KeyManagerFactory kmFactory = KeyManagerFactory.getInstance(this.keyManagerFactoryAlgorithm);
    char[] password = this.getPassword();
    try {
        kmFactory.init(this.getKeyStore(), password);
    } finally {
        if (password != null) {
            Arrays.fill(password, '\0');
        }
    }
    return kmFactory;
}
 
Example #22
Source File: SSLFactory.java    From ts-reaktive with MIT License 5 votes vote down vote up
/**
 * Create an SSL context based on a KeyStore
 * 
 * @param ks A keystore with a private key and certificate chain.
 * @param password the password for the keystore.
 */
public static SSLContext createSSLContext(KeyStore ks, char[] password) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException, CertificateException, UnrecoverableKeyException {
    final SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks, password);
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(ks);
    sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), SecureRandom.getInstance("SHA1PRNG"));
    return sslContext;
}
 
Example #23
Source File: NettySubstitutions.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Alias
Target_io_netty_handler_ssl_JdkSslServerContext(Provider provider,
        X509Certificate[] trustCertCollection, TrustManagerFactory trustManagerFactory,
        X509Certificate[] keyCertChain, PrivateKey key, String keyPassword,
        KeyManagerFactory keyManagerFactory, Iterable<String> ciphers, CipherSuiteFilter cipherFilter,
        ApplicationProtocolConfig apn, long sessionCacheSize, long sessionTimeout,
        ClientAuth clientAuth, String[] protocols, boolean startTls,
        String keyStore)
        throws SSLException {
}
 
Example #24
Source File: ConstantPasswords.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void bad7() throws Exception {
    byte[] bytes = new byte[2];
    char[] pwd = "secret7".toCharArray();
    new PBEKeySpec(pwd);
    new PBEKeySpec(pwd, bytes, 1);
    new PBEKeySpec(pwd, bytes, 1, 1);
    PasswordAuthentication auth = new PasswordAuthentication("user", pwd);
    PasswordCallback callback = new PasswordCallback("str", true);
    callback.setPassword(pwd);
    KeyStore.PasswordProtection protection = new KeyStore.PasswordProtection(pwd);
    KerberosKey key = new KerberosKey(null, pwd, "alg");
    KeyManagerFactory.getInstance("").init(null, pwd);
}
 
Example #25
Source File: NettySslFactory.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * @param config the {@link SSLConfig}.
 * @return an initialized {@link KeyManagerFactory}
 * @throws GeneralSecurityException
 * @throws IOException
 */
static KeyManagerFactory getKeyManagerFactory(SSLConfig config) throws GeneralSecurityException, IOException {
  KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
  KeyStore ks = loadKeyStore(config.sslKeystorePath, config.sslKeystoreType, config.sslKeystorePassword);
  String keyPassword = config.sslKeyPassword.isEmpty() ? config.sslKeystorePassword : config.sslKeyPassword;
  kmf.init(ks, keyPassword.toCharArray());
  return kmf;
}
 
Example #26
Source File: SSLConnectionTest.java    From talk-android with MIT License 5 votes vote down vote up
SSLContext createSSLContext() throws GeneralSecurityException, IOException {
    KeyStore ks = KeyStore.getInstance("JKS");
    File file = new File("src/test/resources/keystore.jks");
    ks.load(new FileInputStream(file), "password".toCharArray());

    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks, "password".toCharArray());

    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(ks);

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    return sslContext;
}
 
Example #27
Source File: SSLContextFactory.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@link SSLContext} instance
 *
 * @param keyStoreFile a p12 or jks file depending on key store type
 * @param keyStorePassword password to access the key store
 * @param keyStoreType type of key store
 * @param trustStoreFile a jks file
 * @param trustStorePassword password to access the trust store
 */
public static SSLContext createInstance(File keyStoreFile, String keyStorePassword, String keyStoreType, File trustStoreFile,
    String trustStorePassword) {
  if (!keyStoreType.equalsIgnoreCase(P12_STORE_TYPE_NAME) && !keyStoreType.equalsIgnoreCase(JKS_STORE_TYPE_NAME)) {
    throw new IllegalArgumentException("Unsupported keyStoreType: " + keyStoreType);
  }

  try {
    // Load KeyStore
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(toInputStream(keyStoreFile), keyStorePassword.toCharArray());

    // Load TrustStore
    KeyStore trustStore = KeyStore.getInstance(JKS_STORE_TYPE_NAME);
    trustStore.load(toInputStream(trustStoreFile), trustStorePassword.toCharArray());

    // Set KeyManger from keyStore
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(DEFAULT_ALGORITHM);
    kmf.init(keyStore, keyStorePassword.toCharArray());

    // Set TrustManager from trustStore
    TrustManagerFactory trustFact = TrustManagerFactory.getInstance(DEFAULT_ALGORITHM);
    trustFact.init(trustStore);

    // Set Context to TLS and initialize it
    SSLContext sslContext = SSLContext.getInstance(DEFAULT_PROTOCOL);
    sslContext.init(kmf.getKeyManagers(), trustFact.getTrustManagers(), null);

    return sslContext;
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example #28
Source File: HttpsUtils.java    From BaseProject with Apache License 2.0 5 votes vote down vote up
private static KeyManager[] prepareKeyManager(InputStream bksFile, String password) {
    try {
        if (bksFile == null || password == null) return null;
        KeyStore clientKeyStore = KeyStore.getInstance("BKS");
        clientKeyStore.load(bksFile, password.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(clientKeyStore, password.toCharArray());
        return kmf.getKeyManagers();
    } catch (Exception e) {
        OkLogger.printStackTrace(e);
    }
    return null;
}
 
Example #29
Source File: Kernel.java    From SPADE with GNU General Public License v3.0 5 votes vote down vote up
private static void setupClientSSLContext() throws Exception
{
    SecureRandom secureRandom = new SecureRandom();
    secureRandom.nextInt();

    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(serverKeyStorePublic);
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(clientKeyStorePrivate, PASSWORD_PRIVATE_KEYSTORE.toCharArray());

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), secureRandom);
    sslSocketFactory = sslContext.getSocketFactory();
}
 
Example #30
Source File: JKSCertInfo.java    From log4j2-elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void applyTo(HttpClientFactory.Builder httpClientFactoryBuilder) {

    try (
            FileInputStream keystoreFile = new FileInputStream(new File(keystorePath));
            FileInputStream truststoreFile = new FileInputStream(new File(truststorePath))
    ) {
        KeyStore keyStore = KeyStore.getInstance("jks");
        keyStore.load(keystoreFile, keystorePassword.toCharArray());
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, keystorePassword.toCharArray());

        KeyStore trustStore = KeyStore.getInstance("jks");
        trustStore.load(truststoreFile, truststorePassword.toCharArray());

        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

        // TODO: add support for hostname verification modes
        httpClientFactoryBuilder.withSslSocketFactory(new SSLConnectionSocketFactory(sslContext));
        httpClientFactoryBuilder.withHttpsIOSessionStrategy(new SSLIOSessionStrategy(sslContext, new NoopHostnameVerifier()));

    } catch (IOException | GeneralSecurityException e) {
        throw new ConfigurationException(configExceptionMessage, e);
    }
}