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:de.brendamour.jpasskit.signing.PKSigningUtil.java

/**
 * Load the keystore from an already opened input stream.
 * /*from w  w  w  .j a va  2s. c om*/
 * The caller is responsible for closing the stream after this method returns successfully or fails.
 * 
 * @param inputStreamOfP12
 *            <code>InputStream</code> containing the signing key store.
 * @param password
 *            Password to access the key store
 * @return Key store loaded from <code>inputStreamOfP12</code>
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 * @throws KeyStoreException
 * @throws NoSuchProviderException
 * @throws IllegalArgumentException
 *             If the parameter <code>inputStreamOfP12</code> is <code>null</code>.
 */
public static KeyStore loadPKCS12File(final InputStream inputStreamOfP12, final String password)
        throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException,
        NoSuchProviderException {
    if (inputStreamOfP12 == null) {
        throw new IllegalArgumentException("InputStream of key store must not be null");
    }
    addBCProvider();
    KeyStore keystore = KeyStore.getInstance("PKCS12");

    keystore.load(inputStreamOfP12, password.toCharArray());
    return keystore;
}

From source file:net.link.util.common.KeyUtils.java

public static KeyStore loadKeyStore(String keystoreType, InputStream keyStoreInputStream,
        char[] keyStorePassword) {

    try {/*  ww w  .j  a v  a 2 s  .c om*/
        KeyStore keyStore = KeyStore.getInstance(keystoreType);
        keyStore.load(keyStoreInputStream, keyStorePassword);

        return keyStore;
    } catch (IOException e) {
        throw new InternalInconsistencyException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new InternalInconsistencyException(e);
    } catch (CertificateException e) {
        throw new InternalInconsistencyException(e);
    } catch (KeyStoreException e) {
        throw new InternalInconsistencyException(e);
    }
}

From source file:net.firejack.platform.web.security.x509.KeyUtils.java

public static KeyPair generate(File keystore) {
    if (keystore == null) {
        throw new IllegalArgumentException("Key Store file should not be null.");
    }/*w  w w .  j  av a2s.  c o m*/

    try {
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        if (keystore.exists()) {
            FileInputStream stream = new FileInputStream(keystore);
            ks.load(stream, SECRET);
            IOUtils.closeQuietly(stream);
        } else {
            ks.load(null, SECRET);
        }

        if (ks.containsAlias(ALIAS)) {
            PrivateKey privateKey = (PrivateKey) ks.getKey(ALIAS, SECRET);
            PublicKey publicKey = ks.getCertificate(ALIAS).getPublicKey();
            return new KeyPair(publicKey, privateKey);
        } else {
            KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
            generator.initialize(KEYSIZE, new SecureRandom());
            return generator.generateKeyPair();
        }
    } catch (Throwable th) {
        logger.error("Failed to initialize key store");
        throw new OpenFlameRuntimeException(th.getMessage(), th);
    }
}

From source file:net.firejack.platform.web.security.x509.KeyUtils.java

public static void add(File keystore, KeyPair pair, String domain) {
    if (keystore == null) {
        throw new IllegalArgumentException("Key Store file should not be null.");
    }/*www  . j  av a 2  s  .co m*/

    try {
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        if (keystore.exists()) {
            FileInputStream stream = new FileInputStream(keystore);
            ks.load(stream, SECRET);
            IOUtils.closeQuietly(stream);
        } else {
            ks.load(null, SECRET);
        }

        if (!ks.containsAlias(ALIAS)) {
            X509Certificate certificate = generateCertificate(domain, 1, pair);

            ks.setKeyEntry(ALIAS, pair.getPrivate(), SECRET, new Certificate[] { certificate });

            FileOutputStream stream = new FileOutputStream(keystore);
            ks.store(stream, SECRET);
            IOUtils.closeQuietly(stream);
        }
    } catch (Throwable th) {
        logger.error("Failed to initialize key store");
        throw new OpenFlameRuntimeException(th.getMessage(), th);
    }
}

From source file:mitm.common.security.crl.GenerateTestCRLs.java

private static void loadCA() throws Exception {
    KeyStore caKeyStore = securityFactory.createKeyStore("PKCS12");

    File file = new File("test/resources/testdata/keys/testCA.p12");

    FileInputStream input = new FileInputStream(file);

    caKeyStore.load(input, "test".toCharArray());

    caCertificate = (X509Certificate) caKeyStore.getCertificate("ca");
    caPrivateKey = (PrivateKey) caKeyStore.getKey("ca", null);

    rootCertificate = (X509Certificate) caKeyStore.getCertificate("root");
    rootPrivateKey = (PrivateKey) caKeyStore.getKey("root", null);

    assertNotNull(caCertificate);//from   www . j  a  v  a2  s. c  o m
    assertNotNull(caPrivateKey);
}

From source file:inet.encode.SecureMonitor.java

private static void createHttpsServer() {
    try {//from  www.ja  v a  2s  .  c  o m
        server = HttpsServer.create(new InetSocketAddress(MONITOR_SERVER_PORT), 0);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        // initialise the keystore
        char[] password = Encoder.KEY_STORE_PASS_PHRASE.toCharArray();
        KeyStore ks = KeyStore.getInstance("JKS");
        FileInputStream fis = new FileInputStream(Encoder.KEY_STORE_PATH);
        ks.load(fis, password);

        // setup the key manager factory
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, password);

        // setup the trust manager factory
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        tmf.init(ks);

        // setup the HTTPS context and parameters
        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

        server.setHttpsConfigurator(new HttpsConfigurator(sslContext));
        server.setExecutor(java.util.concurrent.Executors.newCachedThreadPool());
        server.start();
    } catch (Exception ex) {
        Logger.log(ex);
    }
}

From source file:com.vmware.identity.idm.IdmDataCreator.java

private static KeyPair readKeyStore(CredentialDescriptor cd) throws IOException {
    KeyPair kp = null;//from  w w  w .  j  a  v a  2  s  .  co  m
    InputStream is = null;

    try {
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        char[] stsKeystorePassword = cd.getPassword().toCharArray();
        is = getInputStream(cd.getFilename());
        ks.load(is, stsKeystorePassword);

        kp = new KeyPair();
        kp.setCertificateChain(Arrays.asList(ks.getCertificateChain(cd.getAlias())));
        kp.setPrivateKey((PrivateKey) ks.getKey(cd.getAlias(), stsKeystorePassword));
    } catch (Exception e) {
        logger.debug("Caught exception while reading keystore {}", e.toString());
    } finally {
        if (is != null) {
            is.close();
        }
    }

    return kp;
}

From source file:de.cellular.lib.lightlib.backend.LLRequest.java

/**
 * Creates a {@link DefaultHttpClient} object.
 * //from www.ja  v  a 2 s .c  o m
 * @since 1.0
 * @param _credsProvider
 *            the object contains connect credential info like: User, Pwd, Host etc.
 * @param _ALLOW_ALL_HOSTNAME_VERIFIER_FOR_SSL
 *            true allow all hostname verifier for ssl.
 * @return the {@link DefaultHttpClient} object
 */
public static DefaultHttpClient createHttpClient(CredentialsProvider _credsProvider,
        boolean _ALLOW_ALL_HOSTNAME_VERIFIER_FOR_SSL) {
    // -------------------------------------------------------------------
    // Example for _credsProvider
    //
    // String usr = getUser();
    // String pwd = getPassword();
    // DefaultHttpClient httpclient = new DefaultHttpClient(conMgr, params);
    // CredentialsProvider credsProvider = new BasicCredentialsProvider();
    // credsProvider.setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials(usr, pwd));
    // -------------------------------------------------------------------

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, TIME_OUT);
    HttpConnectionParams.setSoTimeout(params, TIME_OUT);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
    HttpProtocolParams.setUseExpectContinue(params, true);

    SchemeRegistry schReg = new SchemeRegistry();
    PlainSocketFactory plainSocketFactory = PlainSocketFactory.getSocketFactory();
    SSLSocketFactory sslSocketFactory = null;

    if (_ALLOW_ALL_HOSTNAME_VERIFIER_FOR_SSL) {
        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);
            sslSocketFactory = new EasySSLSocketFactory(trustStore);
        } catch (Exception _e) {
            LL.e(_e.toString());
            sslSocketFactory = SSLSocketFactory.getSocketFactory();
        }
        sslSocketFactory
                .setHostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } else {
        sslSocketFactory = SSLSocketFactory.getSocketFactory();
    }
    schReg.register(new Scheme("http", plainSocketFactory, 80));
    schReg.register(new Scheme("https", sslSocketFactory, 443));
    ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);

    DefaultHttpClient httpclient = new DefaultHttpClient(conMgr, params);
    if (_credsProvider != null) {
        httpclient.setCredentialsProvider(_credsProvider);
    }
    return httpclient;
}

From source file:au.edu.monash.merc.capture.util.httpclient.ssl.AuthSSLProtocolSocketFactory.java

private static KeyStore createKeyStore(final URL url, final String password)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    if (url == null) {
        throw new IllegalArgumentException("Keystore url may not be null");
    }/*from w ww .  ja  v a  2s .  c  o  m*/
    LOG.debug("Initializing key store");
    KeyStore keystore = KeyStore.getInstance("jks");
    InputStream is = null;
    try {
        is = url.openStream();
        keystore.load(is, password != null ? password.toCharArray() : null);
    } finally {
        if (is != null)
            is.close();
    }
    return keystore;
}

From source file:com.gsma.iariauth.validator.util.IARIValidatorMain.java

private static KeyStore loadKeyStore(String path, String password) {
    KeyStore ks = null;
    File certKeyFile = new File(path);
    if (!certKeyFile.exists() || !certKeyFile.isFile()) {
        return null;
    }// w w  w.j  a  v  a2  s . c  o m
    char[] pass = password.toCharArray();
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(path);
        try {
            ks = KeyStore.getInstance("jks");
            ks.load(fis, pass);
        } catch (Exception e1) {
            try {
                ks = KeyStore.getInstance("bks", bcProvider);
                ks.load(fis, pass);
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    } catch (FileNotFoundException e) {
    } finally {
        try {
            if (fis != null)
                fis.close();
        } catch (Throwable t) {
        }
    }
    return ks;
}