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:com.ring.ytjojo.ssl.EasySSLSocketFactory.java

private static SSLContext createEasySSLContext() throws IOException {
    try {//  w  w  w  .  ja  v  a2s .  c  o m

        // Client should authenticate itself with the valid certificate to Server.
        InputStream clientStream = AppContext_.getInstance().getResources()
                .openRawResource(R.raw.production_test_client);
        char[] password = "XXXXXXXXXXXXX".toCharArray();

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(clientStream, password);

        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, password);

        // Client should also add the CA certificate obtained from server and create TrustManager from it for the client to validate the 
        // identity of the server.
        KeyStore trustStore = KeyStore.getInstance("BKS");
        InputStream instream = null;
        instream = AppContext_.getInstance().getResources().openRawResource(R.raw.production_test_ca);

        try {
            trustStore.load(instream, "XXXXXXXX".toCharArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                instream.close();
            } catch (Exception ignore) {
            }
        }

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(trustStore);

        // Create an SSLContext that uses our TrustManager & Keystore
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);

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

From source file:com.thesocialcoin.networking.SSL.EasySSLSocketFactory.java

private static SSLContext createEasySSLContext() throws IOException {
    try {/*ww w .j a v  a  2s.c o  m*/

        // Client should authenticate itself with the valid certificate to Server.
        InputStream clientStream = App.getAppContext().getResources()
                .openRawResource(R.raw.production_test_client);
        char[] password = "XXXXXXXXXXXXX".toCharArray();

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(clientStream, password);

        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, password);

        // Client should also add the CA certificate obtained from server and create TrustManager from it for the client to validate the
        // identity of the server.
        KeyStore trustStore = KeyStore.getInstance("BKS");
        InputStream instream = null;
        instream = App.getAppContext().getResources().openRawResource(R.raw.production_test_ca);

        try {
            trustStore.load(instream, "XXXXXXXX".toCharArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                instream.close();
            } catch (Exception ignore) {
            }
        }

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(trustStore);

        // Create an SSLContext that uses our TrustManager & Keystore
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);

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

From source file:be.dnsbelgium.rdap.client.RDAPClient.java

public static KeyStore getKeyStoreFromFile(File file, String type, String password) throws KeyStoreException {
    KeyStore result = KeyStore.getInstance(type);
    FileInputStream fis = null;/* w  w w  . j  a va 2  s. c o  m*/
    try {
        fis = new FileInputStream(file);
        result.load(fis, password.toCharArray());
    } catch (IOException e) {
        LOGGER.error("Could not load keystore file", e);
    } catch (CertificateException e) {
        throw new KeyStoreException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new KeyStoreException(e);
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                LOGGER.debug("Could not close keystore file", e);
            }
        }
    }
    return result;
}

From source file:kr.co.exsoft.eframework.util.LicenseUtil.java

/**
 * ??  ?.//  ww w  .j a va  2  s. com
 * 
 * @param licenseType
 * @param userCount
 * @return String
 */
public static String generateLicenseKey(String licenseType, int userCount) {

    String ksPass = "loveboat";
    String keyPass = "loveboat";
    String alias = "ab942e0f-9e4a-44b9-9f82-0a5f5d48ba12";
    String ret = null;

    try {
        // ??   
        URL url = ClassLoader.getSystemResource("kr/co/exsoft/eframework/cert/exsoft.pfx");
        FileInputStream certfis = new FileInputStream(new File(url.getFile()));

        // Private Key ?.
        BufferedInputStream ksbufin = new BufferedInputStream(certfis);

        KeyStore ks = KeyStore.getInstance("PKCS12");
        ks.load(ksbufin, ksPass.toCharArray());

        PrivateKey key = (PrivateKey) ks.getKey(alias, keyPass.toCharArray());

        // ??  ?.
        ret = spell("EDMsl|" + licenseType + "|" + userCount + "|", key);

    } catch (Exception e) {
        e.printStackTrace();
    }

    return ret;
}

From source file:com.michael.openexercise.mc_network.volleydemo.ssl.EasySSLSocketFactory.java

private static SSLContext createEasySSLContext() throws IOException {
    try {/*from w w  w . j  a v a 2s .  co m*/

        // Client should authenticate itself with the valid certificate to Server.
        InputStream clientStream = VolleySampleApplication.getContext().getResources()
                .openRawResource(R.raw.production_test_client);
        char[] password = "XXXXXXXXXXXXX".toCharArray();

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(clientStream, password);

        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, password);

        // Client should also add the CA certificate obtained from server and create TrustManager from it for the client to validate the
        // identity of the server.
        KeyStore trustStore = KeyStore.getInstance("BKS");
        InputStream instream = null;
        instream = VolleySampleApplication.getContext().getResources()
                .openRawResource(R.raw.production_test_ca);

        try {
            trustStore.load(instream, "XXXXXXXX".toCharArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                instream.close();
            } catch (Exception ignore) {
            }
        }

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(trustStore);

        // Create an SSLContext that uses our TrustManager & Keystore
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);

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

From source file:com.kixeye.chassis.transport.shared.JettyConnectorRegistry.java

/**
 * Register to listen to HTTPS./*w ww . j av a2  s. co m*/
 * 
 * @param server
 * @param address
 * @throws Exception 
 */
public static void registerHttpsConnector(Server server, InetSocketAddress address, boolean selfSigned,
        boolean mutualSsl, String keyStorePath, String keyStoreData, String keyStorePassword,
        String keyManagerPassword, String trustStorePath, String trustStoreData, String trustStorePassword,
        String[] excludedCipherSuites) throws Exception {
    // SSL Context Factory
    SslContextFactory sslContextFactory = new SslContextFactory();

    if (selfSigned) {
        char[] passwordChars = UUID.randomUUID().toString().toCharArray();

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

        keyStore.load(null, passwordChars);

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

        v3CertGen.setSerialNumber(BigInteger.valueOf(new SecureRandom().nextInt()).abs());
        v3CertGen.setIssuerDN(new X509Principal("CN=" + "kixeye.com" + ", OU=None, O=None L=None, C=None"));
        v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
        v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)));
        v3CertGen.setSubjectDN(new X509Principal("CN=" + "kixeye.com" + ", OU=None, O=None L=None, C=None"));

        v3CertGen.setPublicKey(keyPair.getPublic());
        v3CertGen.setSignatureAlgorithm("MD5WithRSAEncryption");

        X509Certificate privateKeyCertificate = v3CertGen.generateX509Certificate(keyPair.getPrivate());

        keyStore.setKeyEntry("selfSigned", keyPair.getPrivate(), passwordChars,
                new java.security.cert.Certificate[] { privateKeyCertificate });

        ByteArrayOutputStream keyStoreBaos = new ByteArrayOutputStream();
        keyStore.store(keyStoreBaos, passwordChars);

        keyStoreData = new String(Hex.encode(keyStoreBaos.toByteArray()), Charsets.UTF_8);
        keyStorePassword = new String(passwordChars);
        keyManagerPassword = keyStorePassword;

        sslContextFactory.setTrustAll(true);
    }

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

    if (StringUtils.isNotBlank(keyStoreData)) {
        keyStore.load(new ByteArrayInputStream(Hex.decode(keyStoreData)), keyStorePassword.toCharArray());
    } else if (StringUtils.isNotBlank(keyStorePath)) {
        try (InputStream inputStream = new DefaultResourceLoader().getResource(keyStorePath).getInputStream()) {
            keyStore.load(inputStream, keyStorePassword.toCharArray());
        }
    }

    sslContextFactory.setKeyStore(keyStore);
    sslContextFactory.setKeyStorePassword(keyStorePassword);
    if (StringUtils.isBlank(keyManagerPassword)) {
        keyManagerPassword = keyStorePassword;
    }
    sslContextFactory.setKeyManagerPassword(keyManagerPassword);
    KeyStore trustStore = null;
    if (StringUtils.isNotBlank(trustStoreData)) {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(new ByteArrayInputStream(Hex.decode(trustStoreData)), trustStorePassword.toCharArray());
    } else if (StringUtils.isNotBlank(trustStorePath)) {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        try (InputStream inputStream = new DefaultResourceLoader().getResource(trustStorePath)
                .getInputStream()) {
            trustStore.load(inputStream, trustStorePassword.toCharArray());
        }
    }
    if (trustStore != null) {
        sslContextFactory.setTrustStore(trustStore);
        sslContextFactory.setTrustStorePassword(trustStorePassword);
    }
    sslContextFactory.setNeedClientAuth(mutualSsl);
    sslContextFactory.setExcludeCipherSuites(excludedCipherSuites);

    // SSL Connector
    ServerConnector connector = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.toString()),
            new HttpConnectionFactory());
    connector.setHost(address.getHostName());
    connector.setPort(address.getPort());

    server.addConnector(connector);
}

From source file:com.dbay.apns4j.tools.ApnsTools.java

public final static SocketFactory createSocketFactory(InputStream keyStore, String password,
        String keystoreType, String algorithm, String protocol)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
        UnrecoverableKeyException, KeyManagementException, CertificateExpiredException {

    char[] pwdChars = password.toCharArray();
    KeyStore ks = KeyStore.getInstance(keystoreType);
    ks.load(keyStore, pwdChars);

    // ??//  www.j  ava  2s.c om
    Enumeration<String> enums = ks.aliases();
    String alias = "";
    if (enums.hasMoreElements()) {
        alias = enums.nextElement();
    }
    if (StringUtils.isNotEmpty(alias)) {
        X509Certificate certificate = (X509Certificate) ks.getCertificate(alias);
        if (null != certificate) {
            String type = certificate.getType();
            int ver = certificate.getVersion();
            String name = certificate.getSubjectDN().getName();
            String serialNumber = certificate.getSerialNumber().toString(16);
            String issuerDN = certificate.getIssuerDN().getName();
            String sigAlgName = certificate.getSigAlgName();
            String publicAlgorithm = certificate.getPublicKey().getAlgorithm();
            Date before = certificate.getNotBefore();
            Date after = certificate.getNotAfter();

            String beforeStr = DateFormatUtils.format(before, "yyyy-MM-dd HH:mm:ss");
            String afterStr = DateFormatUtils.format(after, "yyyy-MM-dd HH:mm:ss");

            // ??
            long expire = DateUtil.getNumberOfDaysBetween(new Date(), after);
            if (expire <= 0) {
                if (LOG.isErrorEnabled()) {
                    LOG.error(
                            "?[{}], [{}], ?[{}], ??[{}], ?[{}], ??[{}], [{}], [{}][{}], ?[{}]",
                            name, type, ver, serialNumber, issuerDN, sigAlgName, publicAlgorithm, beforeStr,
                            afterStr, Math.abs(expire));
                }

                throw new CertificateExpiredException("??[" + Math.abs(expire) + "]");
            }

            if (LOG.isInfoEnabled()) {
                LOG.info(
                        "?[{}], [{}], ?[{}], ??[{}], ?[{}], ??[{}], [{}], [{}][{}], ?[{}]?",
                        name, type, ver, serialNumber, issuerDN, sigAlgName, publicAlgorithm, beforeStr,
                        afterStr, expire);
            }
        }
    }

    KeyManagerFactory kf = KeyManagerFactory.getInstance(algorithm);
    kf.init(ks, pwdChars);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
    tmf.init((KeyStore) null);
    SSLContext context = SSLContext.getInstance(protocol);
    context.init(kf.getKeyManagers(), tmf.getTrustManagers(), null);

    return context.getSocketFactory();
}

From source file:com.ldroid.kwei.common.lib.volley.ssl.EasySSLSocketFactory.java

private static SSLContext createEasySSLContext() throws IOException {
    try {//from   w  w w .  j a  v a2 s. c  o m

        // Client should authenticate itself with the valid certificate to
        // Server.
        InputStream clientStream = MainApp.getContext().getResources()
                .openRawResource(R.raw.production_test_client);
        char[] password = "XXXXXXXXXXXXX".toCharArray();

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(clientStream, password);

        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, password);

        // Client should also add the CA certificate obtained from server
        // and create TrustManager from it for the client to validate the
        // identity of the server.
        KeyStore trustStore = KeyStore.getInstance("BKS");
        InputStream instream = null;
        instream = MainApp.getContext().getResources().openRawResource(R.raw.production_test_ca);

        try {
            trustStore.load(instream, "XXXXXXXX".toCharArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                instream.close();
            } catch (Exception ignore) {
            }
        }

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(trustStore);

        // Create an SSLContext that uses our TrustManager & Keystore
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);

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

From source file:com.vtc.basetube.services.volley.ssl.EasySSLSocketFactory.java

private static SSLContext createEasySSLContext(Context context) throws IOException {
    try {//from w  ww.java  2  s  . com
        // Client should authenticate itself with the valid certificate to
        // Server.
        InputStream clientStream = context.getResources().openRawResource(CERTIFICATE_RESOURCE_CLIENT);
        char[] password = "XXXXXXXXXXXXX".toCharArray();

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(clientStream, password);

        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, password);

        // Client should also add the CA certificate obtained from server
        // and create TrustManager from it for the client to validate the
        // identity of the server.
        KeyStore trustStore = KeyStore.getInstance("BKS");
        InputStream instream = null;
        instream = context.getResources().openRawResource(CERTIFICATE_RESOURCE_CA);

        try {
            trustStore.load(instream, "XXXXXXXX".toCharArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                instream.close();
            } catch (Exception ignore) {
            }
        }

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(trustStore);

        // Create an SSLContext that uses our TrustManager & Keystore
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);

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

From source file:com.mobicage.rogerthat.util.http.HTTPUtil.java

private static KeyStore loadTrustStore() {
    if (sTrustStore == null) {
        String keyStorePassword = "rogerthat";
        try {/*  w w w  .j  a  va2s.c o  m*/
            final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            InputStream instream = App.getContext().getAssets().open("truststore.bks");
            try {
                keyStore.load(instream, keyStorePassword.toCharArray());
            } finally {
                instream.close();
            }
            sTrustStore = keyStore;
        } catch (Exception e) {
            throw new RuntimeException("Could not load keyStore from assets dir", e);
        }
    }
    return sTrustStore;
}