Example usage for java.security KeyStore load

List of usage examples for java.security KeyStore load

Introduction

In this page you can find the example usage for java.security KeyStore load.

Prototype

public final void load(InputStream stream, char[] password)
        throws IOException, NoSuchAlgorithmException, CertificateException 

Source Link

Document

Loads this KeyStore from the given input stream.

Usage

From source file:org.eclipse.mylyn.internal.commons.http.PollingSslProtocolSocketFactory.java

public PollingSslProtocolSocketFactory() {
    KeyManager[] keymanagers = null;
    if (System.getProperty(KEY_STORE) != null && System.getProperty(KEY_STORE_PASSWORD) != null) {
        try {//www  .ja v a  2s  . c  o  m
            String type = System.getProperty(KEY_STORE_TYPE, KeyStore.getDefaultType());
            KeyStore keyStore = KeyStore.getInstance(type);
            char[] password = System.getProperty(KEY_STORE_PASSWORD).toCharArray();
            keyStore.load(new FileInputStream(System.getProperty(KEY_STORE)), password);
            KeyManagerFactory keyManagerFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, password);
            keymanagers = keyManagerFactory.getKeyManagers();
        } catch (Exception e) {
            CommonsHttpPlugin.log(IStatus.ERROR, "Could not initialize keystore", e); //$NON-NLS-1$
        }
    }

    hasKeyManager = keymanagers != null;

    try {
        SSLContext sslContext = SSLContext.getInstance("SSL"); //$NON-NLS-1$
        sslContext.init(keymanagers, new TrustManager[] { new TrustAllTrustManager() }, null);
        this.socketFactory = sslContext.getSocketFactory();
    } catch (Exception e) {
        CommonsHttpPlugin.log(IStatus.ERROR, "Could not initialize SSL context", e); //$NON-NLS-1$
    }
}

From source file:com.trsst.Command.java

public static final void writeKeyPairToFile(KeyPair keyPair, X509Certificate cert, String alias, File file,
        char[] pwd) {
    FileInputStream input = null;
    FileOutputStream output = null;
    try {/*from w  w  w  . j a v  a 2s  . co m*/
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        if (file.exists()) {
            input = new FileInputStream(file);
            keyStore.load(new FileInputStream(file), pwd);
            input.close();
        } else {
            keyStore.load(null); // weird but required
        }

        // save my private key
        keyStore.setKeyEntry(alias, keyPair.getPrivate(), pwd, new X509Certificate[] { cert });

        // store away the keystore
        output = new java.io.FileOutputStream(file);
        keyStore.store(output, pwd);
        output.flush();
    } catch (Exception e) {
        log.error("Error while storing key: " + e.getMessage(), e);
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                // ignore while closing
                log.trace("Error while closing: " + e.getMessage(), e);
            }
        }
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
                // ignore while closing
                log.trace("Error while closing: " + e.getMessage(), e);
            }
        }
    }
}

From source file:io.kodokojo.config.module.SecurityModule.java

@Provides
@Singleton/* w w  w  .  j a va 2 s.c  o  m*/
SSLKeyPair provideSSLKeyPair(SecurityConfig securityConfig) {
    if (securityConfig == null) {
        throw new IllegalArgumentException("securityConfig must be defined.");
    }
    if (StringUtils.isNotBlank(securityConfig.wildcardPemPath())) {

        File pemFile = new File(securityConfig.wildcardPemPath());
        try {
            String content = IOUtils.toString(new FileReader(pemFile));
            String contentPrivate = RSAUtils.extractPrivateKey(content);
            String contentPublic = RSAUtils.extractPublic(content);

            RSAPrivateKey rsaPrivateKey = RSAUtils.readRsaPrivateKey(new StringReader(contentPrivate));
            X509Certificate certificate = RSAUtils.readRsaPublicKey(new StringReader(contentPublic));
            RSAPublicKey rsaPublicKey = (RSAPublicKey) certificate.getPublicKey();

            X509Certificate[] certificates = new X509Certificate[1];
            certificates[0] = certificate;
            LOGGER.info(
                    "Using Wildcard SSL certificat {} from path {}to provide Certificat to all instances of Kodo Kojo. ",
                    certificate.getSubjectDN().toString(), securityConfig.wildcardPemPath());
            return new SSLKeyPair(rsaPrivateKey, rsaPublicKey, certificates);
        } catch (IOException e) {
            throw new IllegalArgumentException("Unable to read pem file " + pemFile.getAbsolutePath() + ".", e);
        }
    } else {
        try {
            KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
            ks.load(new FileInputStream(System.getProperty("javax.net.ssl.keyStore")),
                    System.getProperty("javax.net.ssl.keyStorePassword", "").toCharArray());

            RSAPrivateCrtKey key = (RSAPrivateCrtKey) ks.getKey(securityConfig.sslRootCaKsAlias(),
                    securityConfig.sslRootCaKsPassword().toCharArray());
            if (key == null) {
                return null;
            }

            RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent());

            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(publicKeySpec);
            Certificate[] certificateChain = ks.getCertificateChain(securityConfig.sslRootCaKsAlias());
            List<X509Certificate> x509Certificates = Arrays.asList(certificateChain).stream()
                    .map(c -> (X509Certificate) c).collect(Collectors.toList());
            LOGGER.info(
                    "Using a CA SSL certificat {} from keystore  to provide Certificat to all instances of Kodo Kojo. ",
                    securityConfig.sslRootCaKsAlias(), System.getProperty("javax.net.ssl.keyStore"));
            return new SSLKeyPair(key, publicKey,
                    x509Certificates.toArray(new X509Certificate[x509Certificates.size()]));
        } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException
                | InvalidKeySpecException | CertificateException | IOException e) {

            throw new RuntimeException("Unable to open default Keystore", e);
        }
    }
}

From source file:com.xyproto.archfriend.Web.java

private HttpClient getNewHttpClient() {
    try {//from  w  w  w  . jav  a2  s . com
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:brooklyn.launcher.BrooklynWebServerTest.java

private KeyStore load(String name, String password) throws Exception {
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    FileInputStream instream = new FileInputStream(new File(getFile(name)));
    keystore.load(instream, password.toCharArray());
    return keystore;
}

From source file:com.cellobject.oikos.util.NetworkHelper.java

public HttpClient createHttpClient() {
    try {//from   w  w  w.  j a  v  a 2s .  c om
        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        final SSLSocketFactory sf = new IISSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        final HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        final SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));
        final ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
        return new DefaultHttpClient(ccm, params);
    } catch (final Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:com.linkedin.pinot.common.utils.ClientSSLContextGenerator.java

private KeyManager[] setupKeyManagers() {
    if (_keyStoreFile == null) {
        return null;
    }//from   www .  j a  va2 s  .co  m
    try {
        KeyStore keyStore = KeyStore.getInstance(KEYSTORE_TYPE);
        LOGGER.info("Setting up keystore with file {}", _keyStoreFile);
        keyStore.load(new FileInputStream(new File(_keyStoreFile)), _keyStorePassword.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KEYMANAGER_FACTORY_ALGORITHM);
        kmf.init(keyStore, _keyStorePassword.toCharArray());
        LOGGER.info("Successfully initialized keystore");
        return kmf.getKeyManagers();
    } catch (Exception e) {
        Utils.rethrowException(e);
    }
    return null;
}

From source file:net.sf.ufsc.ftp.FTPSClient.java

public FTPSClient() {
    super();// w  w  w .ja  v  a2 s .  c  o m

    try {
        KeyStore keyStore = KeyStore.getInstance(KEY_STORE_TYPE);
        keyStore.load(null, PASSWORD.toCharArray());

        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());

        keyManagerFactory.init(keyStore, PASSWORD.toCharArray());

        SSLContext context = SSLContext.getInstance(PROTOCOL);
        context.init(keyManagerFactory.getKeyManagers(), new TrustManager[] { new SimpleTrustManager() }, null);

        this.socketFactory = new SecureSocketFactory(context);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:cn.com.mozilla.sync.utils.HttpsTransport.java

public HttpsTransport() {
    // Create SSL socket factory
    if (ALLOW_INVALID_CERTS) {

        try {//from w  w w.  j  av  a2 s .com
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);
            mSslSocketFactory = new EasySSLSocketFactory(trustStore);
        } catch (GeneralSecurityException e) {
            Log.w("Firefoxmini", e.toString());
        } catch (IOException e) {
            Log.w("Firefoxmini", e.toString());
        }
    }
    if (mSslSocketFactory == null) {
        mSslSocketFactory = SSLSocketFactory.getSocketFactory();
    }

    // Create ClientConnectionManager
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("https", mSslSocketFactory, HTTPS_PORT_DEFAULT));
    mClientConMgr = new SingleClientConnManager(sHttpParams, schemeRegistry);
}

From source file:dk.itst.oiosaml.sp.IntegrationTests.java

@Before
public final void setUpServer() throws Exception {
    tmpdir = new File(System.getProperty("java.io.tmpdir") + "/oiosaml-" + Math.random());
    tmpdir.mkdir();/*  w ww  . j a va2  s  .  c  o m*/
    FileUtils.forceMkdir(new File(tmpdir, "metadata/IdP"));
    FileUtils.forceMkdir(new File(tmpdir, "metadata/SP"));

    credential = TestHelper.getCredential();
    EntityDescriptor idpDescriptor = TestHelper.buildEntityDescriptor(credential);
    FileOutputStream fos = new FileOutputStream(new File(tmpdir, "metadata/IdP/gen.xml"));
    IOUtils.write(XMLHelper.nodeToString(SAMLUtil.marshallObject(idpDescriptor)).getBytes(), fos);
    fos.close();

    EntityDescriptor spDescriptor = (EntityDescriptor) SAMLUtil
            .unmarshallElement(getClass().getResourceAsStream("/dk/itst/oiosaml/sp/SPMetadata.xml"));
    fos = new FileOutputStream(new File(tmpdir, "metadata/SP/SPMetadata.xml"));
    IOUtils.write(XMLHelper.nodeToString(SAMLUtil.marshallObject(spDescriptor)).getBytes(), fos);
    fos.close();

    spMetadata = new SPMetadata(spDescriptor, SAMLConstants.SAML20P_NS);
    idpMetadata = new IdpMetadata(SAMLConstants.SAML20P_NS, idpDescriptor);

    fos = new FileOutputStream(new File(tmpdir, "oiosaml-sp.log4j.xml"));
    IOUtils.write(
            "<!DOCTYPE log4j:configuration SYSTEM \"http://logging.apache.org/log4j/docs/api/org/apache/log4j/xml/log4j.dtd\"><log4j:configuration xmlns:log4j=\"http://jakarta.apache.org/log4j/\" debug=\"false\"></log4j:configuration>",
            fos);
    fos.close();

    Properties props = new Properties();
    props.setProperty(Constants.PROP_CERTIFICATE_LOCATION, "keystore");
    props.setProperty(Constants.PROP_CERTIFICATE_PASSWORD, "password");
    props.setProperty(Constants.PROP_LOG_FILE_NAME, "oiosaml-sp.log4j.xml");
    props.setProperty(SAMLUtil.OIOSAML_HOME, tmpdir.getAbsolutePath());
    props.setProperty(Constants.PROP_SESSION_HANDLER_FACTORY, SingleVMSessionHandlerFactory.class.getName());

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    ks.setKeyEntry("oiosaml", credential.getPrivateKey(), "password".toCharArray(),
            new Certificate[] { TestHelper.getCertificate(credential) });
    OutputStream bos = new FileOutputStream(new File(tmpdir, "keystore"));
    ks.store(bos, "password".toCharArray());
    bos.close();

    props.setProperty(Constants.PROP_ASSURANCE_LEVEL, "2");
    props.setProperty(Constants.PROP_IGNORE_CERTPATH, "true");
    fos = new FileOutputStream(new File(tmpdir, "oiosaml-sp.properties"));
    props.store(fos, "Generated");
    fos.close();

    SAMLConfiguration.setSystemConfiguration(null);
    IdpMetadata.setMetadata(null);
    SPMetadata.setMetadata(null);
    System.setProperty(SAMLUtil.OIOSAML_HOME, tmpdir.getAbsolutePath());
    server = new Server(8808);
    WebAppContext wac = new WebAppContext();
    wac.setClassLoader(Thread.currentThread().getContextClassLoader());
    wac.setContextPath("/saml");
    wac.setWar("webapp/");

    server.setHandler(wac);
    server.start();

    client = new WebClient();
    client.setRedirectEnabled(false);
    client.setThrowExceptionOnFailingStatusCode(false);
    handler = new RedirectRefreshHandler();
    client.setRefreshHandler(handler);
}