Example usage for javax.net.ssl KeyManagerFactory init

List of usage examples for javax.net.ssl KeyManagerFactory init

Introduction

In this page you can find the example usage for javax.net.ssl KeyManagerFactory init.

Prototype

public final void init(KeyStore ks, char[] password)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException 

Source Link

Document

Initializes this factory with a source of key material.

Usage

From source file:com.datastax.loader.CqlDelimLoad.java

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);//  ww  w . j a v a 2 s  .co  m

    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();
}

From source file:org.jenkinsci.remoting.engine.HandlerLoopbackLoadStress.java

public HandlerLoopbackLoadStress(Config config)
        throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException,
        UnrecoverableKeyException, KeyManagementException, OperatorCreationException {
    this.config = config;
    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
    gen.initialize(2048); // maximum supported by JVM with export restrictions
    keyPair = gen.generateKeyPair();/* w  ww. j  a  v  a2 s.  c  om*/

    Date now = new Date();
    Date firstDate = new Date(now.getTime() + TimeUnit.DAYS.toMillis(10));
    Date lastDate = new Date(now.getTime() + TimeUnit.DAYS.toMillis(-10));

    SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo
            .getInstance(keyPair.getPublic().getEncoded());

    X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    X500Name subject = nameBuilder.addRDN(BCStyle.CN, getClass().getSimpleName()).addRDN(BCStyle.C, "US")
            .build();

    X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(subject, BigInteger.ONE, firstDate,
            lastDate, subject, subjectPublicKeyInfo);

    JcaX509ExtensionUtils instance = new JcaX509ExtensionUtils();

    certGen.addExtension(X509Extension.subjectKeyIdentifier, false,
            instance.createSubjectKeyIdentifier(subjectPublicKeyInfo));

    ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BOUNCY_CASTLE_PROVIDER)
            .build(keyPair.getPrivate());

    certificate = new JcaX509CertificateConverter().setProvider(BOUNCY_CASTLE_PROVIDER)
            .getCertificate(certGen.build(signer));

    char[] password = "password".toCharArray();

    KeyStore store = KeyStore.getInstance("jks");
    store.load(null, password);
    store.setKeyEntry("alias", keyPair.getPrivate(), password, new Certificate[] { certificate });

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(store, password);

    context = SSLContext.getInstance("TLS");
    context.init(kmf.getKeyManagers(), new TrustManager[] { new BlindTrustX509ExtendedTrustManager() }, null);

    mainHub = IOHub.create(executorService);
    // on windows there is a bug whereby you cannot mix ServerSockets and Sockets on the same selector
    acceptorHub = File.pathSeparatorChar == 59 ? IOHub.create(executorService) : mainHub;
    legacyHub = new NioChannelHub(executorService);
    executorService.submit(legacyHub);
    serverSocketChannel = ServerSocketChannel.open();

    JnlpProtocolHandler handler = null;
    for (JnlpProtocolHandler h : new JnlpProtocolHandlerFactory(executorService).withNioChannelHub(legacyHub)
            .withIOHub(mainHub).withSSLContext(context).withPreferNonBlockingIO(!config.bio)
            .withClientDatabase(new JnlpClientDatabase() {
                @Override
                public boolean exists(String clientName) {
                    return true;
                }

                @Override
                public String getSecretOf(@Nonnull String clientName) {
                    return secretFor(clientName);
                }
            }).withSSLClientAuthRequired(false).handlers()) {
        if (config.name.equals(h.getName())) {
            handler = h;
            break;
        }
    }
    if (handler == null) {
        throw new RuntimeException("Unknown handler: " + config.name);
    }
    this.handler = handler;

    acceptor = new Acceptor(serverSocketChannel);
    runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
    _getProcessCpuTime = _getProcessCpuTime(operatingSystemMXBean);
    garbageCollectorMXBeans = new ArrayList<GarbageCollectorMXBean>(
            ManagementFactory.getGarbageCollectorMXBeans());
    Collections.sort(garbageCollectorMXBeans, new Comparator<GarbageCollectorMXBean>() {
        @Override
        public int compare(GarbageCollectorMXBean o1, GarbageCollectorMXBean o2) {
            return o1.getName().compareTo(o2.getName());
        }
    });
    stats = new Stats();
}

From source file:org.apache.geode.management.internal.cli.commands.ConnectCommand.java

private KeyManager[] getKeyManagers(SSLConfig sslConfig) throws Exception {
    FileInputStream keyStoreStream = null;
    KeyManagerFactory keyManagerFactory = null;

    try {//from   w  w  w. j a  va 2  s  .c  om
        if (StringUtils.isNotBlank(sslConfig.getKeystore())) {
            KeyStore clientKeys = KeyStore.getInstance(sslConfig.getKeystoreType());
            keyStoreStream = new FileInputStream(sslConfig.getKeystore());
            clientKeys.load(keyStoreStream, sslConfig.getKeystorePassword().toCharArray());

            keyManagerFactory = KeyManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(clientKeys, sslConfig.getKeystorePassword().toCharArray());
        }
    } finally {
        if (keyStoreStream != null) {
            keyStoreStream.close();
        }
    }

    return keyManagerFactory != null ? keyManagerFactory.getKeyManagers() : null;
}

From source file:org.deviceconnect.android.message.DevicePluginContext.java

/**
 * SSLContext ?????./*from   w  ww.  j a v a 2s  . com*/
 * <p>
 * ? Web ?????Manager???????????SSLContext ???
 * </p>
 * @param keyStore 
 * @return SSLContext?
 * @throws GeneralSecurityException SSLContext???????
 */
protected SSLContext createSSLContext(final KeyStore keyStore) throws GeneralSecurityException {
    SSLContext sslContext = SSLContext.getInstance("TLS");
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, "0000".toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
            new SecureRandom());
    return sslContext;
}

From source file:android.core.SSLSocketTest.java

/**
 * Loads a keystore from a base64-encoded String. Returns the KeyManager[]
 * for the result./*from   w  w w .jav  a 2  s  . co  m*/
 */
private KeyManager[] getKeyManagers(String keys) throws Exception {
    byte[] bytes = new Base64().decode(keys.getBytes());
    InputStream inputStream = new ByteArrayInputStream(bytes);

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(inputStream, PASSWORD.toCharArray());
    inputStream.close();

    String algorithm = KeyManagerFactory.getDefaultAlgorithm();
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
    keyManagerFactory.init(keyStore, PASSWORD.toCharArray());

    return keyManagerFactory.getKeyManagers();
}

From source file:org.alfresco.encryption.AlfrescoKeyStoreImpl.java

/**
 * {@inheritDoc}/*from  ww  w. j  a  v  a2  s  .c  o  m*/
 */
@Override
public KeyManager[] createKeyManagers() {
    KeyInfoManager keyInfoManager = null;

    try {
        keyInfoManager = getKeyInfoManager(getKeyMetaDataFileLocation());
        KeyStore ks = loadKeyStore(keyStoreParameters, keyInfoManager);

        logger.debug("Initializing key managers");
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());

        String keyStorePassword = keyInfoManager.getKeyStorePassword();
        kmfactory.init(ks, keyStorePassword != null ? keyStorePassword.toCharArray() : null);
        return kmfactory.getKeyManagers();
    } catch (Throwable e) {
        throw new AlfrescoRuntimeException("Unable to create key manager", e);
    } finally {
        if (keyInfoManager != null) {
            keyInfoManager.clear();
        }
    }
}

From source file:org.apache.bookkeeper.tls.TLSContextFactory.java

private KeyManagerFactory initKeyManagerFactory(String keyStoreType, String keyStoreLocation,
        String keyStorePasswordPath) throws SecurityException, KeyStoreException, NoSuchAlgorithmException,
        CertificateException, IOException, UnrecoverableKeyException, InvalidKeySpecException {
    KeyManagerFactory kmf = null;

    if (Strings.isNullOrEmpty(keyStoreLocation)) {
        LOG.error("Key store location cannot be empty when Mutual Authentication is enabled!");
        throw new SecurityException(
                "Key store location cannot be empty when Mutual Authentication is enabled!");
    }/*w w  w .  j a v  a 2s .  c  om*/

    String keyStorePassword = "";
    if (!Strings.isNullOrEmpty(keyStorePasswordPath)) {
        keyStorePassword = getPasswordFromFile(keyStorePasswordPath);
    }

    // Initialize key file
    KeyStore ks = loadKeyStore(keyStoreType, keyStoreLocation, keyStorePassword);
    kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, keyStorePassword.trim().toCharArray());

    return kmf;
}

From source file:org.kuali.kra.s2s.service.impl.GrantsGovConnectorServiceImpl.java

/**
 * This method is to confgiure KeyStore and Truststore for Grants.Gov webservice client
 * @param tlsConfig// w w  w.java  2 s .c  om
 * @param alias
 * @param mulitCampusEnabled
 * @throws S2SException
 */
protected void configureKeyStoreAndTrustStore(TLSClientParameters tlsConfig, String alias,
        boolean mulitCampusEnabled) throws S2SException {
    KeyStore keyStore = S2SCertificateReader.getKeyStore();
    KeyManagerFactory keyManagerFactory;
    try {
        keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        if (alias != null && mulitCampusEnabled) {
            KeyStore keyStoreAlias;
            keyStoreAlias = KeyStore.getInstance(JKS_TYPE);
            Certificate[] certificates = keyStore.getCertificateChain(alias);
            Key key = keyStore.getKey(alias, s2SUtilService.getProperty(KEYSTORE_PASSWORD).toCharArray());
            keyStoreAlias.load(null, null);
            keyStoreAlias.setKeyEntry(alias, key, s2SUtilService.getProperty(KEYSTORE_PASSWORD).toCharArray(),
                    certificates);
            keyManagerFactory.init(keyStoreAlias, s2SUtilService.getProperty(KEYSTORE_PASSWORD).toCharArray());
        } else {
            keyManagerFactory.init(keyStore, s2SUtilService.getProperty(KEYSTORE_PASSWORD).toCharArray());
        }
        KeyManager[] km = keyManagerFactory.getKeyManagers();
        tlsConfig.setKeyManagers(km);
        KeyStore trustStore = S2SCertificateReader.getTrustStore();
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);
        TrustManager[] tm = trustManagerFactory.getTrustManagers();
        tlsConfig.setTrustManagers(tm);
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (KeyStoreException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (UnrecoverableKeyException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (CertificateException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (IOException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    }
}

From source file:org.jivesoftware.smack.XMPPConnection.java

/**
 * The server has indicated that TLS negotiation can start. We now need to secure the
 * existing plain connection and perform a handshake. This method won't return until the
 * connection has finished the handshake or an error occured while securing the connection.
 *
 * @throws Exception if an exception occurs.
 *///from   w w w  .  j av  a 2  s  .  co m
void proceedTLSReceived() throws Exception {
    SSLContext context = SSLContext.getInstance("TLS");
    KeyStore ks = null;
    KeyManager[] kms = null;
    PasswordCallback pcb = null;

    if (config.getCallbackHandler() == null) {
        ks = null;
    } else {
        //System.out.println("Keystore type: "+configuration.getKeystoreType());
        if (config.getKeystoreType().equals("NONE")) {
            ks = null;
            pcb = null;
        } else if (config.getKeystoreType().equals("PKCS11")) {
            try {
                Constructor c = Class.forName("sun.security.pkcs11.SunPKCS11")
                        .getConstructor(InputStream.class);
                String pkcs11Config = "name = SmartCard\nlibrary = " + config.getPKCS11Library();
                ByteArrayInputStream config = new ByteArrayInputStream(pkcs11Config.getBytes());
                Provider p = (Provider) c.newInstance(config);
                Security.addProvider(p);
                ks = KeyStore.getInstance("PKCS11", p);
                pcb = new PasswordCallback("PKCS11 Password: ", false);
                this.config.getCallbackHandler().handle(new Callback[] { pcb });
                ks.load(null, pcb.getPassword());
            } catch (Exception e) {
                ks = null;
                pcb = null;
            }
        } else if (config.getKeystoreType().equals("Apple")) {
            ks = KeyStore.getInstance("KeychainStore", "Apple");
            ks.load(null, null);
            //pcb = new PasswordCallback("Apple Keychain",false);
            //pcb.setPassword(null);
        } else {
            ks = KeyStore.getInstance(config.getKeystoreType());
            try {
                pcb = new PasswordCallback("Keystore Password: ", false);
                config.getCallbackHandler().handle(new Callback[] { pcb });
                ks.load(new FileInputStream(config.getKeystorePath()), pcb.getPassword());
            } catch (Exception e) {
                ks = null;
                pcb = null;
            }
        }
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        try {
            if (pcb == null) {
                kmf.init(ks, null);
            } else {
                kmf.init(ks, pcb.getPassword());
                pcb.clearPassword();
            }
            kms = kmf.getKeyManagers();
        } catch (NullPointerException npe) {
            kms = null;
        }
    }

    // Verify certificate presented by the server
    context.init(kms, new javax.net.ssl.TrustManager[] { new ServerTrustManager(getServiceName(), config) },
            new java.security.SecureRandom());
    Socket plain = socket;
    // Secure the plain connection
    socket = context.getSocketFactory().createSocket(plain, plain.getInetAddress().getHostName(),
            plain.getPort(), true);
    socket.setSoTimeout(0);
    socket.setKeepAlive(true);
    // Initialize the reader and writer with the new secured version
    initReaderAndWriter();
    // Proceed to do the handshake
    ((SSLSocket) socket).startHandshake();
    //if (((SSLSocket) socket).getWantClientAuth()) {
    //    System.err.println("Connection wants client auth");
    //}
    //else if (((SSLSocket) socket).getNeedClientAuth()) {
    //    System.err.println("Connection needs client auth");
    //}
    //else {
    //    System.err.println("Connection does not require client auth");
    // }
    // Set that TLS was successful
    usingTLS = true;

    // Set the new  writer to use
    packetWriter.setWriter(writer);
    // Send a new opening stream to the server
    packetWriter.openStream();
}