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:talkeeg.httpserver.HttpServer.java

private NHttpConnectionFactory<DefaultNHttpServerConnection> createConnectionFactory() {
    NHttpConnectionFactory<DefaultNHttpServerConnection> connFactory;
    if (config.isUseTLS()) {
        try {//w  w  w .jav a2 s.  c om
            KeyStore keystore = KeyStore.getInstance("jks");
            char[] password = new char[0];
            keystore.load(null, password);
            final X509Certificate certificate = certManager.getCertificate(OwnedKeyType.USER);
            KeyStore.PrivateKeyEntry entry = new KeyStore.PrivateKeyEntry(
                    ownedKeysManager.getPrivateKey(OwnedKeyType.USER), new Certificate[] { certificate });

            keystore.setEntry("", entry, new KeyStore.PasswordProtection(password));
            KeyManagerFactory kmfactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmfactory.init(keystore, password);
            final KeyManager[] keymanagers = kmfactory.getKeyManagers();
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(keymanagers, null, null);
            connFactory = new SSLNHttpServerConnectionFactory(sslcontext, null, ConnectionConfig.DEFAULT);
        } catch (Exception e) {
            throw new RuntimeException("Can not initialise SSL.", e);
        }
    } else {
        connFactory = new DefaultNHttpServerConnectionFactory(ConnectionConfig.DEFAULT);
    }
    return connFactory;
}

From source file:be.fedict.hsm.model.KeyStoreLoaderBean.java

private Map<String, PrivateKeyEntry> loadPKCS12(KeyStoreEntity keyStoreEntity) throws KeyStoreException,
        NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableEntryException {
    String keyStorePath = keyStoreEntity.getPath();
    InputStream keyStoreInputStream = new FileInputStream(keyStorePath);
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    String keyStorePassword = keyStoreEntity.getPassword();
    keyStore.load(keyStoreInputStream, keyStorePassword.toCharArray());
    return loadKeys(keyStoreEntity, keyStore, keyStorePassword);
}

From source file:jp.pigumer.mqtt.Client.java

Optional<KeyStore> loadKeyStore() {
    X509Certificate cert;// w w w. jav a2  s  .  co  m

    if (caFile == null) {
        return Optional.empty();
    }
    try (InputStream is = caFile.getInputStream()) {
        InputStreamReader isr = new InputStreamReader(is);
        PEMParser parser = new PEMParser(isr);
        X509CertificateHolder holder = (X509CertificateHolder) parser.readObject();
        cert = new JcaX509CertificateConverter().getCertificate(holder);
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", cert);
        return Optional.of(keyStore);
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "failed load", e);
        return Optional.empty();
    }
}

From source file:com.amazon.alexa.avs.companion.ProvisioningClient.java

private SSLSocketFactory getPinnedSSLSocketFactory(Context context) throws Exception {
    InputStream caCertInputStream = null;
    try {//from  w ww .  ja v  a 2  s  . c  o  m
        caCertInputStream = context.getResources().openRawResource(R.raw.ca);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Certificate caCert = cf.generateCertificate(caCertInputStream);

        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setCertificateEntry("myca", caCert);

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

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
        return sslContext.getSocketFactory();
    } finally {
        IOUtils.closeQuietly(caCertInputStream);
    }
}

From source file:org.commonjava.indy.httprox.ProxyHttpsWildcardHostCertTest.java

private KeyStore getTrustStore(File jks) throws Exception {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    try (FileInputStream instream = new FileInputStream(jks)) {
        trustStore.load(instream, "passwd".toCharArray());
    }/*w ww.jav  a 2  s  .c  o m*/
    return trustStore;
}

From source file:com.adito.install.actions.UploadExistingCertificateAction.java

private boolean validateKeyStore(String keyStoreType, String password, File keystoreFile) {
    InputStream inputStream = null;
    try {/*from  w w  w .j ava 2s  .c  o m*/
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        inputStream = new FileInputStream(keystoreFile);
        keyStore.load(inputStream, password.toCharArray());
        return true;
    } catch (Exception e) {
        log.error("Validation of key store failed", e);
        return false;
    } finally {
        Util.closeStream(inputStream);
    }
}

From source file:gui.configurar.GerarAssinatura.java

String assinar() {
    String senha = tSenha.getText();
    String c = tContribuinte.getText() + tDev.getText();
    if (certificado == null) {
        Msg.show("Escolha o certificado");
        return "";
    }/*from  w  ww  .jav a  2 s  .  c  o  m*/
    try {
        KeyStore keystore = KeyStore.getInstance("PKCS12");
        keystore.load(new FileInputStream(certificado), senha.toCharArray());
        ArrayList<String> apelidos = new ArrayList<String>();
        Enumeration<String> aliases = keystore.aliases();
        while (aliases.hasMoreElements()) {
            apelidos.add(aliases.nextElement());
        }
        PrivateKey key = (PrivateKey) keystore.getKey(apelidos.get(0), senha.toCharArray());
        Signature assinatura = Signature.getInstance("SHA256withRSA");
        assinatura.initSign(key);
        byte[] bytes = c.getBytes();
        assinatura.update(bytes);
        byte[] assinado = assinatura.sign();
        String strAssinado = Base64.encodeBase64String(assinado);
        return strAssinado;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

From source file:com.appfirst.communication.AFHttpClient.java

public DefaultHttpClient getAFHttpClient() {
    try {//from   w w w . j  av  a  2 s .  c  om
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        try {
            trustStore.load(null, null);
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        SSLSocketFactory sf = new AFSSLSocketFactory(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 (NoSuchAlgorithmException nsae) {
        Log.e(TAG, nsae.getMessage());
        return new DefaultHttpClient();
    } catch (KeyManagementException kme) {
        Log.e(TAG, kme.getMessage());
        return new DefaultHttpClient();
    } catch (KeyStoreException kse) {
        Log.e(TAG, kse.getMessage());
        return new DefaultHttpClient();
    } catch (UnrecoverableKeyException uke) {
        Log.e(TAG, uke.getMessage());
        return new DefaultHttpClient();
    }
}

From source file:org.surveydroid.android.coms.SDHttpClient.java

private SSLSocketFactory newSslSocketFactory() {
    try {//  w w  w .java 2s  . c om
        KeyStore trusted = KeyStore.getInstance("BKS");
        InputStream in = ctxt.getResources().openRawResource(R.raw.sd_keystore);
        try {
            trusted.load(in, PASSWORD.toCharArray());
        } catch (CertificateException e) {
            Util.e(null, TAG, "Cert Exception: " + Util.fmt(e));
            throw new AssertionError(e);
        } finally {
            in.close();
        }
        SSLSocketFactory sf = new SSLSocketFactory(trusted);
        //TODO look into this
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        return sf;
    } catch (Exception e) {
        Util.e(ctxt, TAG, Util.fmt(e));
        throw new AssertionError(e);
    }
}

From source file:mitm.common.security.keystore.KeyStoreLoader.java

public KeyStore loadKeyStore(File file, char[] password) throws IOException, KeyStoreException,
        NoSuchProviderException, NoSuchAlgorithmException, CertificateException {
    if (file == null) {
        throw new IOException("file cannot be null");
    }/*from  w  w  w .  j ava2 s  .  co  m*/

    if (!file.exists()) {
        throw new FileNotFoundException("file does not exist");
    }

    if (StringUtils.isEmpty(keyStoreType)) {
        determineKeyStoreTypeFromFile(file);
    }

    KeyStore keyStore = KeyStore.getInstance(keyStoreType);

    InputStream input = new FileInputStream(file);

    try {
        keyStore.load(input, password);
    } finally {
        IOUtils.closeQuietly(input);
    }

    return keyStore;
}