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:edu.washington.iam.tools.IamConnectionManager.java

protected void initManagers() {

    // trust managers
    /**//ww w. j  ava 2 s  . com
           try {
               TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            
               X509Certificate cert = null;
               if (caFilename!=null) cert = readCertificate(caFilename);
               log.debug("init trust mgr " + cert);
               trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
               trustStore.load(null, null);
               trustStore.setCertificateEntry("CACERT", cert);
               tmf.init(trustStore);
               trustManagers = tmf.getTrustManagers();
           } catch (Exception e) {
               log.error("cacert error: " + e);
           }
     **/
    trustManagers = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
            return;
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
            return;
        }
    } };

    // key managers
    if (certFilename != null && keyFilename != null) {
        try {
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null, null);

            X509Certificate cert = readCertificate(certFilename);
            PKCS1 pkcs = new PKCS1();
            PrivateKey key = pkcs.readKey(keyFilename);

            X509Certificate[] chain = new X509Certificate[1];
            chain[0] = cert;
            keyStore.setKeyEntry("CERT", (Key) key, "pw".toCharArray(), chain);

            kmf.init(keyStore, "pw".toCharArray());
            keyManagers = kmf.getKeyManagers();
        } catch (Exception e) {
            log.error("cert/key error: " + e);
        }
    }

}

From source file:com.isecpartners.gizmo.HttpRequest.java

private KeyManagerFactory createKeyManagerFactory(String cname) throws KeyStoreException,
        NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException,
        InvalidKeyException, SignatureException, NoSuchProviderException, NoCertException {
    X509Certificate cert = KeyStoreManager.getCertificateByHostname(cname);
    cybervillains.ca.KeyStoreManager.getCertificateByHostname(cname);

    if (cert == null) {
        throw new NoCertException();
    }//from ww  w  . j  a  v  a2  s .c  o  m

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, pass);

    ks.setCertificateEntry(cname, cert);
    ks.setKeyEntry(cname, KeyStoreManager.getPrivateKeyForLocalCert(cert), pass,
            new X509Certificate[] { cert });

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

    return kmf;
}

From source file:com.twinsoft.convertigo.engine.MySSLSocketFactory.java

private SSLContext createEasySSLContext()
        throws NoSuchProviderException, NoSuchAlgorithmException, KeyManagementException,
        UnrecoverableKeyException, KeyStoreException, CertificateException, IOException {
    Engine.logCertificateManager.debug("(MySSLSocketFactory) Creating SSL context");

    String algorithm = KeyManagerFactory.getDefaultAlgorithm();
    Engine.logCertificateManager.debug("(MySSLSocketFactory) Using KeyManager algorithm " + algorithm);

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);

    String keyStoreType = keyStore.endsWith(".pkcs11") ? "pkcs11" : "pkcs12";
    Engine.logCertificateManager.debug("(MySSLSocketFactory) Key store type: " + keyStoreType);

    String alias = null;//from   www .  j  av  a2s.c o m
    KeyStore ks, ts;
    char[] passPhrase;

    if (keyStore.equals("") || (keyStore.endsWith(".udv"))) {
        ks = KeyStore.getInstance(keyStoreType);
        ks.load(null, keyStorePassword.toCharArray());
        kmf.init(ks, null);
    } else {
        File file = new File(keyStore);

        Properties properties = new Properties();
        properties.load(
                new FileInputStream(Engine.CERTIFICATES_PATH + CertificateManager.STORES_PROPERTIES_FILE_NAME));
        String p = properties.getProperty(file.getName(), "");
        int i = p.indexOf('/');
        if (i != -1) {
            alias = p.substring(i + 1);
        }

        if (keyStoreType.equals("pkcs11")) {
            String providerName = file.getName();
            providerName = "SunPKCS11-" + providerName.substring(0, providerName.lastIndexOf('.'));
            Engine.logCertificateManager.debug("(MySSLSocketFactory) Provider name: '" + providerName + "'");

            String pinCode;
            if (i == -1) {
                pinCode = Crypto2.decodeFromHexString(p);
            } else {
                pinCode = Crypto2.decodeFromHexString(p.substring(0, i));
            }

            Engine.logCertificateManager.debug("(MySSLSocketFactory) PIN code: " + pinCode);

            ks = KeyStore.getInstance("pkcs11", providerName);
            ks.load((InputStream) null, pinCode.toCharArray());
            kmf.init(ks, null);
        } else {
            ks = KeyStore.getInstance(keyStoreType);
            passPhrase = keyStorePassword.toCharArray();
            ks.load(new FileInputStream(keyStore), passPhrase);
            kmf.init(ks, passPhrase);
        }
    }
    Engine.logCertificateManager.debug("(MySSLSocketFactory) Client alias: "
            + (alias == null ? "<to be chosen by the security implementor>" : alias));

    ts = KeyStore.getInstance("jks");
    passPhrase = trustStorePassword.toCharArray();
    if (trustStore.equals(""))
        ts.load(null, passPhrase);
    else
        ts.load(new FileInputStream(trustStore), passPhrase);

    algorithm = TrustManagerFactory.getDefaultAlgorithm();
    Engine.logCertificateManager.debug("(MySSLSocketFactory) Using TrustManager algorithm " + algorithm);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
    tmf.init(ts);

    TrustManager[] tm = { TRUST_MANAGER };

    MyX509KeyManager xkm = new MyX509KeyManager((X509KeyManager) kmf.getKeyManagers()[0], ks, ts, alias);

    Engine.logCertificateManager
            .debug("(MySSLSocketFactory) trusting all certificates : " + trustAllServerCertificates);

    //SSLContext context = SSLContext.getInstance("SSLv3");
    SSLContext context = SSLContext.getInstance("TLS");
    if (trustAllServerCertificates)
        context.init(new KeyManager[] { xkm }, tm, null);
    else
        context.init(new KeyManager[] { xkm }, tmf.getTrustManagers(), null);

    Engine.logCertificateManager.debug("(MySSLSocketFactory) SSL context created: " + context.getProtocol());
    return context;
}

From source file:org.nectarframework.base.service.nanohttp.NanoHttpService.java

/**
 * Creates an SSLSocketFactory for HTTPS. Pass a KeyStore resource with your
 * certificate and passphrase/*from  w  w w .  ja v  a  2s . c  om*/
 */
public ServerSocket makeSSLServerSocket(String keyAndTrustStoreClasspathPath, char[] passphrase)
        throws IOException {
    try {
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        InputStream keystoreStream = new FileInputStream(new File(keyAndTrustStoreClasspathPath));

        keystore.load(keystoreStream, passphrase);
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keystore, passphrase);

        SSLServerSocketFactory res = null;
        try {
            TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keystore);
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
            res = ctx.getServerSocketFactory();

        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }

        SSLServerSocket ss = null;
        ss = (SSLServerSocket) res.createServerSocket();
        ss.setEnabledProtocols(ss.getSupportedProtocols());
        ss.setUseClientMode(false);
        ss.setWantClientAuth(false);
        ss.setNeedClientAuth(false);

        return ss;

    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }
}

From source file:org.apache.jmeter.protocol.amf.proxy.AmfProxy.java

/**
 * Get SSL connection from hashmap, creating it if necessary.
 *
 * @param host//from  w  w w. jav a 2 s . c  o  m
 * @return a ssl socket factory
 * @throws IOException
 */
private SSLSocketFactory getSSLSocketFactory(String host) throws IOException {
    synchronized (hashHost) {
        if (hashHost.containsKey(host)) {
            log.debug("Good, already in map, host=" + host);
            return hashHost.get(host);
        }
        InputStream in = getCertificate();
        Exception except = null;
        if (in != null) {
            KeyStore ks = null;
            KeyManagerFactory kmf = null;
            SSLContext sslcontext = null;
            try {
                ks = KeyStore.getInstance(KEYSTORE_TYPE);
                ks.load(in, KEYSTORE_PASSWORD);
                kmf = KeyManagerFactory.getInstance(KEYMANAGERFACTORY);
                kmf.init(ks, KEY_PASSWORD);
                sslcontext = SSLContext.getInstance(SSLCONTEXT_PROTOCOL);
                sslcontext.init(kmf.getKeyManagers(), null, null);
                SSLSocketFactory sslFactory = sslcontext.getSocketFactory();
                hashHost.put(host, sslFactory);
                log.info("KeyStore for SSL loaded OK and put host in map (" + host + ")");
                return sslFactory;
            } catch (NoSuchAlgorithmException e) {
                except = e;
            } catch (KeyManagementException e) {
                except = e;
            } catch (KeyStoreException e) {
                except = e;
            } catch (UnrecoverableKeyException e) {
                except = e;
            } catch (CertificateException e) {
                except = e;
            } finally {
                if (except != null) {
                    log.error("Problem with SSL certificate", except);
                }
                IOUtils.closeQuietly(in);
            }
        } else {
            throw new IOException("Unable to read keystore");
        }
        return null;
    }
}

From source file:org.parosproxy.paros.network.SSLConnector.java

public SSLSocketFactory getTunnelSSLSocketFactory(String hostname) {

    //   SSLServerSocketFactory ssf = null;
    // set up key manager to do server authentication

    //   KeyStore ks;
    try {//from  w w  w. ja  v a2 s .  co  m
        SSLContext ctx = SSLContext.getInstance(SSL);
        // Normally "SunX509", "IbmX509"...
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());

        SslCertificateService scs = CachedSslCertifificateServiceImpl.getService();
        KeyStore ks = scs.createCertForHost(hostname);

        kmf.init(ks, SslCertificateService.PASSPHRASE);
        java.security.SecureRandom x = new java.security.SecureRandom();
        x.setSeed(System.currentTimeMillis());
        ctx.init(kmf.getKeyManagers(), null, x);

        SSLSocketFactory tunnelSSLFactory = createDecoratedServerSslSocketFactory(ctx.getSocketFactory());

        return tunnelSSLFactory;

    } catch (NoSuchAlgorithmException | KeyStoreException | CertificateException | UnrecoverableKeyException
            | KeyManagementException | InvalidKeyException | NoSuchProviderException | SignatureException
            | IOException e) {
        // Turn into RuntimeException. How to handle this error in a user
        // friendly way?
        throw new RuntimeException(e);
    }
}

From source file:org.codice.ddf.cxf.client.impl.SecureCxfClientFactoryImpl.java

@SuppressWarnings("squid:S3776")
private void configureConduit(ClientConfiguration clientConfig) {
    HTTPConduit httpConduit = clientConfig.getHttpConduit();
    if (httpConduit == null) {
        LOGGER.info("HTTPConduit was null for {}. Unable to configure security.", this);
        return;/*from  w ww. j  a v  a2  s. c o  m*/
    }

    if (allowRedirects) {
        HTTPClientPolicy clientPolicy = httpConduit.getClient();
        if (clientPolicy != null) {
            clientPolicy.setAutoRedirect(true);
            Bus bus = clientConfig.getBus();
            if (bus != null) {
                bus.getProperties().put(AUTO_REDIRECT_ALLOW_REL_URI, true);
                bus.getProperties().put(AUTO_REDIRECT_MAX_SAME_URI_COUNT, getSameUriRedirectMax());
            }
        }
    }

    TLSClientParameters tlsParams = httpConduit.getTlsClientParameters();
    if (tlsParams == null) {
        tlsParams = new TLSClientParameters();
    }

    tlsParams.setDisableCNCheck(disableCnCheck);

    tlsParams.setUseHttpsURLConnectionDefaultHostnameVerifier(!disableCnCheck);
    String cipherSuites = System.getProperty("https.cipherSuites");
    if (cipherSuites != null) {
        tlsParams.setCipherSuites(Arrays.asList(cipherSuites.split(",")));
    }

    KeyStore keyStore = null;
    KeyStore trustStore = null;
    try {
        keyStore = SecurityConstants.newKeystore();
        trustStore = SecurityConstants.newTruststore();
    } catch (KeyStoreException e) {
        LOGGER.debug("Unable to create keystore instance of type {}",
                System.getProperty(SecurityConstants.KEYSTORE_TYPE), e);
    }
    Path keyStoreFile;
    if (keyInfo != null && StringUtils.isNotBlank(keyInfo.getKeystorePath())) {
        keyStoreFile = Paths.get(keyInfo.getKeystorePath());
    } else {
        keyStoreFile = Paths.get(SecurityConstants.getKeystorePath());
    }

    Path trustStoreFile = Paths.get(SecurityConstants.getTruststorePath());
    String ddfHome = System.getProperty("ddf.home");
    if (ddfHome != null) {
        Path ddfHomePath = Paths.get(ddfHome);
        if (!keyStoreFile.isAbsolute()) {
            keyStoreFile = Paths.get(ddfHomePath.toString(), keyStoreFile.toString());
        }
        if (!trustStoreFile.isAbsolute()) {
            trustStoreFile = Paths.get(ddfHomePath.toString(), trustStoreFile.toString());
        }
    }
    String keyStorePassword = SecurityConstants.getKeystorePassword();
    String trustStorePassword = SecurityConstants.getTruststorePassword();
    if (!Files.isReadable(keyStoreFile) || !Files.isReadable(trustStoreFile)) {
        LOGGER.debug("Unable to read system key/trust store files: [ {} ] [ {} ]", keyStoreFile,
                trustStoreFile);
        return;
    }
    try (InputStream kfis = Files.newInputStream(keyStoreFile)) {
        if (keyStore != null) {
            keyStore.load(kfis, keyStorePassword.toCharArray());
        }
    } catch (NoSuchAlgorithmException | CertificateException | IOException e) {
        LOGGER.debug("Unable to load system key file.", e);
    }
    try (InputStream tfis = Files.newInputStream(trustStoreFile)) {
        if (trustStore != null) {
            trustStore.load(tfis, trustStorePassword.toCharArray());
        }
    } catch (NoSuchAlgorithmException | CertificateException | IOException e) {
        LOGGER.debug("Unable to load system trust file.", e);
    }

    KeyManager[] keyManagers = null;
    try {
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
        keyManagers = keyManagerFactory.getKeyManagers();
        tlsParams.setKeyManagers(keyManagers);
    } catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException e) {
        LOGGER.debug("Unable to initialize KeyManagerFactory.", e);
    }

    TrustManager[] trustManagers = null;
    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);
        trustManagers = trustManagerFactory.getTrustManagers();
        tlsParams.setTrustManagers(trustManagers);
    } catch (NoSuchAlgorithmException | KeyStoreException e) {
        LOGGER.debug("Unable to initialize TrustManagerFactory.", e);
    }

    if (keyInfo != null) {
        LOGGER.trace("Using keystore file: {}, alias: {}", keyStoreFile, keyInfo.getAlias());
        tlsParams.setUseHttpsURLConnectionDefaultSslSocketFactory(false);
        tlsParams.setCertAlias(keyInfo.getAlias());
        try {
            if (keyManagers == null) {
                throw new KeyManagementException("keyManagers was null");
            }

            boolean validProtocolFound = false;
            String validProtocolsStr = System.getProperty("jdk.tls.client.protocols");
            if (StringUtils.isNotBlank(validProtocolsStr)) {
                String[] validProtocols = validProtocolsStr.split(",");
                for (String validProtocol : validProtocols) {
                    if (validProtocol.equals(sslProtocol)) {
                        validProtocolFound = true;
                        break;
                    }
                }
                if (!validProtocolFound) {
                    LOGGER.error("{} is not in list of valid SSL protocols {}", sslProtocol, validProtocolsStr);
                }

            } else {
                validProtocolFound = true;
            }
            if (validProtocolFound) {
                tlsParams.setSSLSocketFactory(
                        getSSLSocketFactory(sslProtocol, keyInfo.getAlias(), keyManagers, trustManagers));
            }
        } catch (KeyManagementException | NoSuchAlgorithmException e) {
            LOGGER.debug("Unable to override default SSL Socket Factory", e);
        }
    } else {
        tlsParams.setUseHttpsURLConnectionDefaultSslSocketFactory(true);
        tlsParams.setCertAlias(SystemBaseUrl.INTERNAL.getHost());
    }

    httpConduit.setTlsClientParameters(tlsParams);
}

From source file:ddf.security.realm.sts.StsRealm.java

/**
 * Setup key store for SSL client./*w  ww . ja  v a  2s .co  m*/
 */
private void setupKeyStore(TLSClientParameters tlsParams, String keyStorePath, String keyStorePassword) {
    File keyStoreFile = new File(keyStorePath);

    if (keyStoreFile.exists() && keyStorePassword != null) {
        FileInputStream fis = null;
        KeyStore keyStore = null;

        try {
            keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            fis = new FileInputStream(keyStoreFile);

            LOGGER.debug("Loading keyStore");
            keyStore.load(fis, keyStorePassword.toCharArray());

            KeyManagerFactory keyFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyFactory.init(keyStore, keyStorePassword.toCharArray());
            LOGGER.debug("key manager factory initialized");
            KeyManager[] km = keyFactory.getKeyManagers();
            tlsParams.setKeyManagers(km);
        } catch (FileNotFoundException e) {
            LOGGER.error("Unable to find SSL store: " + keyStorePath, e);
        } catch (IOException e) {
            LOGGER.error("Unable to load key store. " + keyStoreFile, e);
        } catch (CertificateException e) {
            LOGGER.error("Unable to load certificates from key store. " + keyStoreFile, e);
        } catch (KeyStoreException e) {
            LOGGER.error("Unable to read key store: ", e);
        } catch (NoSuchAlgorithmException e) {
            LOGGER.error("Problems creating SSL socket. Usually this is "
                    + "referring to the certificate sent by the server not being trusted by the client.", e);
        } catch (UnrecoverableKeyException e) {
            LOGGER.error("Unable to read key store: ", e);
        } finally {
            IOUtils.closeQuietly(fis);
        }

    }
}

From source file:org.apache.nifi.processors.grpc.InvokeGRPC.java

/**
 * Whenever this processor is triggered, we need to construct a client in order to communicate
 * with the configured gRPC service./*  w w  w.j a va 2s.  c  om*/
 *
 * @param context the processor context
 */
@OnScheduled
public void initializeClient(final ProcessContext context) throws Exception {

    channelReference.set(null);
    blockingStubReference.set(null);
    final ComponentLog logger = getLogger();

    final String host = context.getProperty(PROP_SERVICE_HOST).getValue();
    final int port = context.getProperty(PROP_SERVICE_PORT).asInteger();
    final Integer maxMessageSize = context.getProperty(PROP_MAX_MESSAGE_SIZE).asDataSize(DataUnit.B).intValue();
    String userAgent = USER_AGENT_PREFIX;
    try {
        userAgent += "_" + InetAddress.getLocalHost().getHostName();
    } catch (final UnknownHostException e) {
        logger.warn("Unable to determine local hostname. Defaulting gRPC user agent to {}.",
                new Object[] { USER_AGENT_PREFIX }, e);
    }

    final NettyChannelBuilder nettyChannelBuilder = NettyChannelBuilder.forAddress(host, port)
            // supports both gzip and plaintext, but will compress by default.
            .compressorRegistry(CompressorRegistry.getDefaultInstance())
            .decompressorRegistry(DecompressorRegistry.getDefaultInstance())
            .maxInboundMessageSize(maxMessageSize).userAgent(userAgent);

    // configure whether or not we're using secure comms
    final boolean useSecure = context.getProperty(PROP_USE_SECURE).asBoolean();
    final SSLContextService sslContextService = context.getProperty(PROP_SSL_CONTEXT_SERVICE)
            .asControllerService(SSLContextService.class);
    final SSLContext sslContext = sslContextService == null ? null
            : sslContextService.createSSLContext(SSLContextService.ClientAuth.NONE);

    if (useSecure && sslContext != null) {
        SslContextBuilder sslContextBuilder = GrpcSslContexts.forClient();
        if (StringUtils.isNotBlank(sslContextService.getKeyStoreFile())) {
            final KeyManagerFactory keyManagerFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm(), sslContext.getProvider());
            final KeyStore keyStore = KeyStore.getInstance(sslContextService.getKeyStoreType());
            try (final InputStream is = new FileInputStream(sslContextService.getKeyStoreFile())) {
                keyStore.load(is, sslContextService.getKeyStorePassword().toCharArray());
            }
            keyManagerFactory.init(keyStore, sslContextService.getKeyStorePassword().toCharArray());
            sslContextBuilder.keyManager(keyManagerFactory);
        }

        if (StringUtils.isNotBlank(sslContextService.getTrustStoreFile())) {
            final TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm(), sslContext.getProvider());
            final KeyStore trustStore = KeyStore.getInstance(sslContextService.getTrustStoreType());
            try (final InputStream is = new FileInputStream(sslContextService.getTrustStoreFile())) {
                trustStore.load(is, sslContextService.getTrustStorePassword().toCharArray());
            }
            trustManagerFactory.init(trustStore);
            sslContextBuilder.trustManager(trustManagerFactory);
        }
        nettyChannelBuilder.sslContext(sslContextBuilder.build());

    } else {
        nettyChannelBuilder.usePlaintext(true);
    }

    final ManagedChannel channel = nettyChannelBuilder.build();
    final FlowFileServiceGrpc.FlowFileServiceBlockingStub blockingStub = FlowFileServiceGrpc
            .newBlockingStub(channel);
    channelReference.set(channel);
    blockingStubReference.set(blockingStub);
}