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:Main.java

/**
 * Check if the file provide is PKCS12//w  w w.j a  v  a2 s  .c  o  m
 * @param cert certificate to be validated
 * @param pass password to be provided
 * @throws Exception to indicate an invalid certificate
 */
public static void validate(byte[] cert, String pass) throws Exception {

    try {
        KeyStore keyStore = KeyStore.getInstance(ALGORITHM);
        keyStore.load(new ByteArrayInputStream(cert), pass.toCharArray());
    } catch (Exception e) {
        throw new Exception("Certificate is not valid!", e);
    }
}

From source file:com.jonbanjo.ssl.JfSSLScheme.java

public static Scheme getScheme() {

    FileInputStream fis = null;//from  w ww  .  j a  va  2  s .  com
    Scheme scheme;

    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());

        try {
            fis = CupsPrintApp.getContext().openFileInput(trustfile);
            trustStore.load(fis, password.toCharArray());
        } catch (Exception e) {
            trustStore.load(null, null);
        }

        SSLSocketFactory sf = new AdditionalKeyStoresSSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        scheme = new Scheme("https", sf, 443);
    } catch (Exception e) {
        scheme = getDefaultScheme();
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (Exception e1) {
            }
        }
    }
    return scheme;
}

From source file:com.android.providers.downloads.ui.network.SslSocketFactory.java

private static KeyStore createKeyStore(InputStream keyStore, String password)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException {
    KeyStore key = KeyStore.getInstance(KeyStore.getDefaultType());
    try {// w w w .  j a  v a2  s .c om
        key.load(keyStore, password.toCharArray());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        try {
            key.load(null, null);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
    return key;
}

From source file:com.linkage.crm.csb.sign.CtSignature.java

/**
 * .// ww  w .  j  a va2s  . co  m
 * 
 * @param pwd String 
 * @param alias String 
 * @param priKeyFile 
 * @return Signature 
 */
public static Signature createSignatureForSign(String pwd, String alias, String priKeyFile) {
    try {
        logger.debug("keypath=============" + priKeyFile);
        KeyStore ks = KeyStore.getInstance("JKS");
        FileInputStream ksfis = new FileInputStream(priKeyFile);
        BufferedInputStream ksbufin = new BufferedInputStream(ksfis);
        char[] kpass = pwd.toCharArray();
        ks.load(ksbufin, kpass);
        PrivateKey priKey = (PrivateKey) ks.getKey(alias, kpass);
        Signature rsa = Signature.getInstance("SHA1withDSA");
        rsa.initSign(priKey);
        return rsa;
    } catch (Exception ex) {
        logger.error("errors appeared while trying to signature", ex);
        return null;
    }
}

From source file:ru.elifantiev.yandex.SSLHttpClientFactory.java

public static HttpClient getNewHttpClient() {
    try {//from   w  ww  .  j  av a  2  s .  c o  m
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new YandexSSLSocketFactory(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:Main.java

public static boolean isCACertificateInstalled(File fileCA, String type, char[] password)
        throws KeyStoreException {

    KeyStore keyStoreCA = null;//from   w  ww .j  a va2 s  .  c om
    try {
        keyStoreCA = KeyStore.getInstance(type/*, "BC"*/);
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (fileCA.exists() && fileCA.canRead()) {
        try {
            FileInputStream fileCert = new FileInputStream(fileCA);
            keyStoreCA.load(fileCert, password);
            fileCert.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (java.security.cert.CertificateException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Enumeration ex = keyStoreCA.aliases();
        Date exportFilename = null;
        String caAliasValue = "";

        while (ex.hasMoreElements()) {
            String is = (String) ex.nextElement();
            Date lastStoredDate = keyStoreCA.getCreationDate(is);
            if (exportFilename == null || lastStoredDate.after(exportFilename)) {
                exportFilename = lastStoredDate;
                caAliasValue = is;
            }
        }

        try {
            return keyStoreCA.getKey(caAliasValue, password) != null;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnrecoverableKeyException e) {
            e.printStackTrace();
        }
    }
    return false;
}

From source file:com.cloudseal.spring.client.namespace.CloudSealKeyManagerImpl.java

protected static KeyStore createKeyStore(Resource storeFile, String storePass, String storeType) {
    InputStream inputStream = null;
    try {//w  w  w .j a v  a 2s  . co m
        inputStream = storeFile.getInputStream();
        KeyStore ks = KeyStore.getInstance(storeType);
        ks.load(inputStream, storePass.toCharArray());
        return ks;
    } catch (Exception e) {
        throw new RuntimeException("Error initializing keystore", e);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:Main.java

/**
 * Generate a SSLSocketFactory wich checks the certificate given
 * @param context Context to use/*from w  ww  .j av  a 2s.  c  o  m*/
 * @param rResource int with url of the resource to read the certificate
 * @parma password String to use with certificate
 * @return SSLSocketFactory generated to validate this certificate
 */
public static SSLSocketFactory newSslSocketFactory(Context context, int rResource, String password)
        throws CertificateException, NoSuchProviderException, KeyStoreException, NoSuchAlgorithmException,
        IOException, UnrecoverableKeyException, KeyManagementException {

    // Get an instance of the Bouncy Castle KeyStore format
    KeyStore trusted = KeyStore.getInstance("BKS");
    // Get the raw resource, which contains the keystore with
    // your trusted certificates (root and any intermediate certs)
    InputStream is = context.getApplicationContext().getResources().openRawResource(rResource);

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
    X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(is);
    String alias = "alias";//cert.getSubjectX500Principal().getName();

    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null);
    trustStore.setCertificateEntry(alias, cert);
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
    kmf.init(trustStore, null);
    KeyManager[] keyManagers = kmf.getKeyManagers();

    TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
    tmf.init(trustStore);
    TrustManager[] trustManagers = tmf.getTrustManagers();

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagers, trustManagers, null);
    return sslContext.getSocketFactory();

}

From source file:Main.java

public static SocketFactory getSocketFactoryWithCustomCA(InputStream stream) throws CertificateException,
        KeyStoreException, IOException, NoSuchAlgorithmException, KeyManagementException {

    // Load CAs from an InputStream
    // (could be from a resource or ByteArrayInputStream or ...)
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    InputStream caInput = new BufferedInputStream(stream);
    Certificate ca;/*from   w  w  w .  java  2 s  . co m*/
    try {
        ca = cf.generateCertificate(caInput);
        System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
    } finally {
        try {
            caInput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", ca);

    // Create a TrustManager that trusts the CAs in our KeyStore
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keyStore);

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

    return context.getSocketFactory();
}

From source file:com.jt.https.test.send.java

public static String PostTo(String content) {
    String responseMessage = null;
    String filePath = "";
    if (!filePath.endsWith("/")) {
        filePath = filePath + "/";
    }/*from   w w w.j a  v a2 s .c  om*/
    HttpClient httpclient = new DefaultHttpClient();
    try {
        KeyStore keystore = KeyStore.getInstance("jks");
        KeyStore trustStore = KeyStore.getInstance("jks");

        FileInputStream keystoreInstream = new FileInputStream(
                new File("F:\\temp\\?\\lz\\\\bis-stg-sdb.jks"));
        FileInputStream trustStoreInstream = new FileInputStream(
                new File("F:\\temp\\?\\lz\\\\EXV_GROUP_BIS_IFRONT_JTLZX_100.jks"));
        //FileInputStream keystoreInstream = new FileInputStream(new File("F:\\temp\\?\\lz\\\\pingan2jiangtai_test.jks"));
        //FileInputStream trustStoreInstream = new FileInputStream(new File("F:\\temp\\?\\lz\\\\pingan2jiangtai_test_trust.jks"));
        try {
            keystore.load(keystoreInstream, "123456".toCharArray());
            trustStore.load(trustStoreInstream, "paic1234".toCharArray());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (CertificateException e) {
            e.printStackTrace();
        } finally {
            keystoreInstream.close();
            trustStoreInstream.close();
        }
        SSLSocketFactory socketFactory = new SSLSocketFactory(SSLSocketFactory.SSL, keystore, "123456",
                trustStore, null, new TrustStrategy() {
                    public boolean isTrusted(X509Certificate[] chain, String authType)
                            throws CertificateException {
                        return true;
                    }
                }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme sch = new Scheme("https", 8107, socketFactory);

        httpclient.getConnectionManager().getSchemeRegistry().register(sch);
        HttpPost post = new HttpPost("https://222.68.184.181:8107");

        StringEntity entity = new StringEntity(content, "text/html", "UTF-8");
        post.setEntity(entity);
        HttpResponse res = httpclient.execute(post);
        HttpEntity resEntity = res.getEntity();
        if (resEntity != null) {
            responseMessage = convertStreamToString(resEntity.getContent());
            System.out.println("???" + content);
            System.out.println("?" + responseMessage);
        }

    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } finally {
        httpclient.getConnectionManager().shutdown();
    }

    return responseMessage;
}