Example usage for java.security KeyStore getInstance

List of usage examples for java.security KeyStore getInstance

Introduction

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

Prototype

public static KeyStore getInstance(String type) throws KeyStoreException 

Source Link

Document

Returns a keystore object of the specified type.

Usage

From source file:cn.com.loopj.android.http.MySSLSocketFactory.java

/**
 * Gets a KeyStore containing the Certificate
 *
 * @param cert InputStream of the Certificate
 * @return KeyStore/*from w ww  .j av a 2 s  . c  o  m*/
 */
public static KeyStore getKeystoreOfCA(InputStream cert) {

    // Load CAs from an InputStream
    InputStream caInput = null;
    Certificate ca = null;
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        caInput = new BufferedInputStream(cert);
        ca = cf.generateCertificate(caInput);
    } catch (CertificateException e1) {
        e1.printStackTrace();
    } finally {
        try {
            if (caInput != null) {
                caInput.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = null;
    try {
        keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", ca);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return keyStore;
}

From source file:com.gravspace.core.HttpServer.java

public static void start(String[] args) throws Exception {

    int port = 8082;
    if (args.length >= 1) {
        port = Integer.parseInt(args[0]);
    }//from w ww  .j  ava 2 s . c  o  m

    ActorSystem system = ActorSystem.create("Application-System");
    Properties config = new Properties();
    config.load(HttpServer.class.getResourceAsStream("/megapode.conf"));
    ActorRef master = system.actorOf(Props.create(CoordinatingActor.class, config), "Coordinator");

    // Set up the HTTP protocol processor
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate())
            .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl())
            .build();

    // Set up request handlers
    UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();
    reqistry.register("*", new HttpHandler(system, master));

    // Set up the HTTP service
    HttpService httpService = new HttpService(httpproc, reqistry);

    SSLServerSocketFactory sf = null;
    if (port == 8443) {
        // Initialize SSL context
        ClassLoader cl = HttpServer.class.getClassLoader();
        URL url = cl.getResource("my.keystore");
        if (url == null) {
            System.out.println("Keystore not found");
            System.exit(1);
        }
        KeyStore keystore = KeyStore.getInstance("jks");
        keystore.load(url.openStream(), "secret".toCharArray());
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmfactory.init(keystore, "secret".toCharArray());
        KeyManager[] keymanagers = kmfactory.getKeyManagers();
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(keymanagers, null, null);
        sf = sslcontext.getServerSocketFactory();
    }

    RequestListenerThread t = new RequestListenerThread(port, httpService, sf);
    t.setDaemon(false);
    t.start();

    t.join();
}

From source file:immf.MyWiser.java

private SSLSocketFactory createSslSocketFactory(String keystoreFile, String keyType, String keypasswd) {
    InputStream keyis = null;/*from   ww  w .  ja v  a  2  s. com*/
    try {
        keyis = new FileInputStream(keystoreFile);
        KeyStore keyStore = KeyStore.getInstance(keyType);
        keyStore.load(keyis, keypasswd.toCharArray());

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(keyStore, keypasswd.toCharArray());

        SSLContext context = SSLContext.getInstance("TLS");

        context.init(kmf.getKeyManagers(), null, new SecureRandom());
        return context.getSocketFactory();
    } catch (Exception e) {
        e.printStackTrace();
        return (SSLSocketFactory) SSLSocketFactory.getDefault();
    } finally {
        try {
            keyis.close();
        } catch (Exception e) {
        }
    }
}

From source file:org.openiot.gsn.http.rest.RestRemoteWrapper.java

public boolean initialize() {
    try {/*from   w  w w. j  a  v  a  2s  .  c  o m*/
        initParams = new RemoteWrapperParamParser(getActiveAddressBean(), false);
        httpclient = new DefaultHttpClient(getHttpClientParams(initParams.getTimeout()));
        // Init the http client
        if (initParams.isSSLRequired()) {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(new FileInputStream(new File("conf/servertestkeystore")),
                    Main.getContainerConfig().getSSLKeyStorePassword().toCharArray());
            SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
            socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            int sslPort = Main.getContainerConfig().getSSLPort() > 0 ? Main.getContainerConfig().getSSLPort()
                    : ContainerConfig.DEFAULT_SSL_PORT;
            Scheme sch = new Scheme("https", socketFactory, sslPort);
            httpclient.getConnectionManager().getSchemeRegistry().register(sch);
        }
        Scheme plainsch = new Scheme("http", PlainSocketFactory.getSocketFactory(),
                Main.getContainerConfig().getContainerPort());
        httpclient.getConnectionManager().getSchemeRegistry().register(plainsch);
        //
        lastReceivedTimestamp = initParams.getStartTime();
        structure = connectToRemote();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return false;
    }
    return true;
}

From source file:monasca.common.middleware.HttpClientPoolFactory.java

private static KeyStore loadKeystore(String type, String keyStore, String keyPass) throws Exception {
    final KeyStore ks = KeyStore.getInstance("jks");
    if ((keyStore != null) && !keyStore.isEmpty()) {
        File keystoreFile = new File(keyStore);
        if (!keystoreFile.canRead()) {
            throw new FileNotFoundException(String.format("%s '%s' is not readable", type, keyStore));
        }//from  w w  w. j a  v a 2  s . c o m
        try (FileInputStream is1 = new FileInputStream(keystoreFile)) {
            ks.load(is1, keyPass.toCharArray());
        } catch (Exception e) {
            String errorMessage = String.format("Unable to open %s '%s': %s", type, keyStore, e.getMessage());
            logger.error(errorMessage);
            throw new Exception(errorMessage, e);
        }
    } else {
        ks.load(null, null);
    }
    return ks;
}

From source file:ddf.security.settings.impl.SecuritySettingsServiceImpl.java

private KeyStore createKeyStore(String path, String password) {
    KeyStore keyStore = null;/*from w ww  .ja v  a  2  s .co  m*/
    File keyStoreFile = new File(path);
    if (keyStoreFile.exists() && StringUtils.isNotBlank(password)) {
        FileInputStream fis = null;
        try {
            keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            fis = new FileInputStream(keyStoreFile);
            LOGGER.debug("Loading trustStore");
            keyStore.load(fis, password.toCharArray());
        } catch (KeyStoreException | CertificateException e) {
            LOGGER.warn("Issue while trying to load ");
        } catch (IOException e) {
            LOGGER.warn("Unable to load keystore file from path" + path, e);
        } catch (NoSuchAlgorithmException nsae) {
            LOGGER.warn("JVM implementation does not come with default keystore type", nsae);
        } finally {
            IOUtils.closeQuietly(fis);
        }
    }
    return keyStore;
}

From source file:com.blackboard.LearnServer.java

private AbstractHttpClient getTrustAllSSLHttpClient() {
    try {/*  w ww .j a  va2s  .co  m*/
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new TrustAllSSLSocketFactory(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) {
        System.out.println("WARNING: Could not create Trust All SSL client, using default" + e.getMessage());
        return new DefaultHttpClient();
    }
}

From source file:com.mgmtp.perfload.core.client.web.ssl.LtSSLSocketFactory.java

private KeyStore createStore(final URL url, final char[] password, final String type)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
    log.debug("Initializing key store");

    KeyStore keystore = KeyStore.getInstance(type);
    InputStream is = null;/*from  www  . j  ava 2  s. c om*/
    try {
        is = url.openStream();
        keystore.load(is, password);
        return keystore;
    } finally {
        closeQuietly(is);
    }
}

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);/*  w  w  w  . j a  v  a 2s . c o m*/

    // ??
    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.github.technosf.posterer.models.KeyStoreBean.java

/**
 * Instantiates a {@code KeyStoreBean} wrapping the given keystore
 * <p>/*from  w  w  w  . j  av a2s. c  o m*/
 * Loads the Key Store file into a {@code KeyStore} and checks the password. If the Key Store
 * can be accessed successfully, validation is successful..
 * 
 * @param file
 *            the KeyStore file
 * @param password
 *            the Key Store password
 * @throws KeyStoreBeanException
 *             Thrown when a {@code KeyStoreBean} cannot be created.
 */
public KeyStoreBean(final File keyStoreFile, final String keyStorePassword) throws KeyStoreBeanException {
    file = keyStoreFile;
    password = keyStorePassword;

    InputStream inputStream = null;

    /*
     * Check file existence
     */
    if (keyStoreFile == null || !keyStoreFile.exists() || !keyStoreFile.canRead())
    // Key Store File cannot be read
    {
        throw new KeyStoreBeanException("Cannot read Key Store file");
    }

    try
    // to get the file input stream
    {
        inputStream = Files.newInputStream(keyStoreFile.toPath(), StandardOpenOption.READ);
    } catch (IOException e) {
        throw new KeyStoreBeanException("Error reading Key Store file", e);
    }

    // Get the file name and extension
    fileName = FilenameUtils.getName(keyStoreFile.getName());
    String fileExtension = FilenameUtils.getExtension(keyStoreFile.getName().toLowerCase());

    /*
     * Identify keystore type, and create an instance
     */
    try {
        switch (fileExtension) {
        case "p12":
            keyStore = KeyStore.getInstance("PKCS12");
            break;
        case "jks":
            keyStore = KeyStore.getInstance("JKS");
            break;
        default:
            throw new KeyStoreBeanException(String.format("Unknown keystore extention: [%1$s]", fileExtension));
        }
    } catch (KeyStoreException e) {
        throw new KeyStoreBeanException("Cannot get keystore instance");
    }

    /*
     * Load the keystore data into the keystore instance
     */
    try {
        keyStore.load(inputStream, password.toCharArray());
    } catch (NoSuchAlgorithmException | CertificateException | IOException e) {
        throw new KeyStoreBeanException("Cannot load the KeyStore", e);
    }

    /*
     * Key store loaded, so config the bean
     */
    try {
        type = keyStore.getType();
        size = keyStore.size();

        Enumeration<String> aliasIterator = keyStore.aliases();
        while (aliasIterator.hasMoreElements()) {
            String alias = aliasIterator.nextElement();
            certificates.put(alias, keyStore.getCertificate(alias));
        }
    } catch (KeyStoreException e) {
        throw new KeyStoreBeanException("Cannot process the KeyStore", e);
    }
}