Example usage for java.security KeyStore getCertificate

List of usage examples for java.security KeyStore getCertificate

Introduction

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

Prototype

public final Certificate getCertificate(String alias) throws KeyStoreException 

Source Link

Document

Returns the certificate associated with the given alias.

Usage

From source file:org.lealone.cluster.security.SSLFactory.java

public static SSLContext createSSLContext(EncryptionOptions options, boolean buildTruststore)
        throws IOException {
    FileInputStream tsf = null;//from ww  w  .  j  av a  2  s . co m
    FileInputStream ksf = null;
    SSLContext ctx;
    try {
        ctx = SSLContext.getInstance(options.protocol);
        TrustManager[] trustManagers = null;

        if (buildTruststore) {
            tsf = new FileInputStream(options.truststore);
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(options.algorithm);
            KeyStore ts = KeyStore.getInstance(options.store_type);
            ts.load(tsf, options.truststore_password.toCharArray());
            tmf.init(ts);
            trustManagers = tmf.getTrustManagers();
        }

        ksf = new FileInputStream(options.keystore);
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(options.algorithm);
        KeyStore ks = KeyStore.getInstance(options.store_type);
        ks.load(ksf, options.keystore_password.toCharArray());
        if (!checkedExpiry) {
            for (Enumeration<String> aliases = ks.aliases(); aliases.hasMoreElements();) {
                String alias = aliases.nextElement();
                if (ks.getCertificate(alias).getType().equals("X.509")) {
                    Date expires = ((X509Certificate) ks.getCertificate(alias)).getNotAfter();
                    if (expires.before(new Date()))
                        logger.warn("Certificate for {} expired on {}", alias, expires);
                }
            }
            checkedExpiry = true;
        }
        kmf.init(ks, options.keystore_password.toCharArray());

        ctx.init(kmf.getKeyManagers(), trustManagers, null);

    } catch (Exception e) {
        throw new IOException("Error creating the initializing the SSL Context", e);
    } finally {
        FileUtils.closeQuietly(tsf);
        FileUtils.closeQuietly(ksf);
    }
    return ctx;
}

From source file:org.apache.cassandra.security.SSLFactory.java

@SuppressWarnings("resource")
public static SSLContext createSSLContext(EncryptionOptions options, boolean buildTruststore)
        throws IOException {
    FileInputStream tsf = null;//  w w  w  .  ja  v a2 s.c om
    FileInputStream ksf = null;
    SSLContext ctx;
    try {
        ctx = SSLContext.getInstance(options.protocol);
        TrustManager[] trustManagers = null;

        if (buildTruststore) {
            tsf = new FileInputStream(options.truststore);
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(options.algorithm);
            KeyStore ts = KeyStore.getInstance(options.store_type);
            ts.load(tsf, options.truststore_password.toCharArray());
            tmf.init(ts);
            trustManagers = tmf.getTrustManagers();
        }

        ksf = new FileInputStream(options.keystore);
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(options.algorithm);
        KeyStore ks = KeyStore.getInstance(options.store_type);
        ks.load(ksf, options.keystore_password.toCharArray());
        if (!checkedExpiry) {
            for (Enumeration<String> aliases = ks.aliases(); aliases.hasMoreElements();) {
                String alias = aliases.nextElement();
                if (ks.getCertificate(alias).getType().equals("X.509")) {
                    Date expires = ((X509Certificate) ks.getCertificate(alias)).getNotAfter();
                    if (expires.before(new Date()))
                        logger.warn("Certificate for {} expired on {}", alias, expires);
                }
            }
            checkedExpiry = true;
        }
        kmf.init(ks, options.keystore_password.toCharArray());

        ctx.init(kmf.getKeyManagers(), trustManagers, null);

    } catch (Exception e) {
        throw new IOException("Error creating the initializing the SSL Context", e);
    } finally {
        FileUtils.closeQuietly(tsf);
        FileUtils.closeQuietly(ksf);
    }
    return ctx;
}

From source file:learn.encryption.ssl.SSLContext_Https.java

/**
 * @description javaSSLContext/* ww w  .ja  v a  2 s  .c  o m*/
 * @description https?, SSLContext (NoHttp?SecureRandombug)
 * @description client.ks?server
 * @description ??
 * @description ????getSSLContext2()
 */
//@SuppressLint("TrulyRandom")
public static SSLContext getSSLContext() {
    SSLContext sslContext = null;
    try {
        sslContext = SSLContext.getInstance("TLS");
        // ??, ??assets
        InputStream inputStream = new FileInputStream(new File("D:\\tomcatcert\\server.ks"));
        //App.getInstance().getAssets().open("srca.cer");

        // ??
        CertificateFactory cerFactory = CertificateFactory.getInstance("X.509");

        // ?KeyStore
        KeyStore keyStore = KeyStore.getInstance("jks");
        keyStore.load(inputStream, "123456".toCharArray());
        //Certificate cer = cerFactory.generateCertificate(inputStream);
        Certificate cer = keyStore.getCertificate("clientKey");
        keyStore.setCertificateEntry("trust", cer);

        // KeyStorekeyManagerFactory
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, "123456".toCharArray());

        // KeyStoreTrustManagerFactory
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);

        // ?SSLContext
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
                new SecureRandom());
    } catch (Exception e) {
        e.printStackTrace();
    }

    return sslContext;
}

From source file:com.glaf.core.security.SecurityUtils.java

/**
 * keystore?//  ww w.ja  va2 s.  c  om
 * 
 * @return X509Certificate ?
 */
public static X509Certificate getCertFromKeystore(InputStream keystoreInputStream, String alias,
        String password) {
    try {
        X509Certificate x509cert = null;
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        ks.load(keystoreInputStream, password.toCharArray());
        x509cert = (X509Certificate) ks.getCertificate(alias);
        return x509cert;
    } catch (Exception ex) {
        throw new SecurityException(ex);
    }
}

From source file:com.cloudbees.jenkins.support.impl.RootCAs.java

public static void getRootCAList(StringWriter writer) {
    KeyStore instance = null;
    try {/*from   w  w w. j  av  a 2  s  .  c o m*/
        instance = KeyStore.getInstance(KeyStore.getDefaultType());
        Enumeration<String> aliases = instance.aliases();
        while (aliases.hasMoreElements()) {
            String s = aliases.nextElement();
            writer.append("========");
            writer.append("Alias: " + s);
            writer.append(instance.getCertificate(s).getPublicKey().toString());
            writer.append("Trusted certificate: " + instance.isCertificateEntry(s));
        }
    } catch (KeyStoreException e) {
        writer.write(Functions.printThrowable(e));
    }
}

From source file:org.apache.airavata.credential.store.client.TestSSLClient.java

public static void testCertificateCredential(CredentialStoreService.Client client) {
    try {/*from   w w w .  ja va 2  s  . c o m*/
        CertificateCredential certificateCredential = new CertificateCredential();
        CommunityUser communityUser = new CommunityUser("testGateway", "test", "test@ddsd");
        certificateCredential.setCommunityUser(communityUser);
        X509Certificate[] x509Certificates = new X509Certificate[1];
        KeyStore ks = KeyStore.getInstance("JKS");
        File keyStoreFile = new File(
                "/Users/smarru/code/airavata-master/modules/configuration/server/src/main/resources/airavata.jks");
        FileInputStream fis = new FileInputStream(keyStoreFile);
        char[] password = "airavata".toCharArray();
        ks.load(fis, password);
        x509Certificates[0] = (X509Certificate) ks.getCertificate("airavata");
        Base64 encoder = new Base64(64);
        String cert_begin = "-----BEGIN CERTIFICATE-----\n";
        String end_cert = "-----END CERTIFICATE-----";
        byte[] derCert = x509Certificates[0].getEncoded();
        String pemCertPre = new String(encoder.encode(derCert));
        String pemCert = cert_begin + pemCertPre + end_cert;
        certificateCredential.setX509Cert(pemCert);
        String token = client.addCertificateCredential(certificateCredential);
        System.out.println("Certificate Token :" + token);
        CertificateCredential credential = client.getCertificateCredential(token, "testGateway");
        System.out.println("certificate : " + credential.getX509Cert());
        System.out.println("gateway name  : " + credential.getCommunityUser().getGatewayName());
    } catch (TTransportException e) {
        e.printStackTrace();
    } catch (TException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.soyatec.windowsazure.internal.util.ssl.SslUtil.java

/**
 * Create SSLContext by given/*  w w w.  ja v a 2  s  .c o m*/
 * keyStoreUrl,keyStorePassword,trustStoreUrl,trustStorePassword,certAlias
 * 
 * @param keyStoreUrl
 *            the keyStore URL
 * @param keyStorePassword
 *            the keyStore password
 * @param trustStoreUrl
 *            the trustStore URL
 * @param trustStorePassword
 *            the trustStore password
 * @param certAlias
 *            the alias name
 * @return the new SSLContext object
 * @throws Exception
 */
@SuppressWarnings("deprecation")
public static SSLContext createSSLContext(String keyStoreUrl, String keyStorePassword, String trustStoreUrl,
        String trustStorePassword, String certAlias) throws Exception {

    KeyManager[] keymanagers = null;
    TrustManager[] trustmanagers = null;

    KeyStore keystore = getKeyStore(new File(keyStoreUrl).toURL(), keyStorePassword);

    PrivateKey privateKey = (PrivateKey) keystore.getKey(certAlias, keyStorePassword.toCharArray());
    X509Certificate cert = (X509Certificate) keystore.getCertificate(certAlias);

    keymanagers = createKeyManagers(keystore, keyStorePassword);
    for (int i = 0; i < keymanagers.length; i++) {

        if (keymanagers[i] instanceof X509ExtendedKeyManager) {
            keymanagers[i] = new HttpsX509KeyManager((X509ExtendedKeyManager) keymanagers[i], certAlias,
                    privateKey, cert);
        }

    }
    SSLContext sslcontext = SSLContext.getInstance("TLS");
    KeyStore trustStore = getKeyStore(new File(trustStoreUrl).toURL(), trustStorePassword);
    trustmanagers = createTrustManagers(trustStore);
    for (int i = 0; i < trustmanagers.length; i++) {
        if (trustmanagers[i] instanceof X509TrustManager) {
            trustmanagers[i] = new HttpsX509TrustManager((X509TrustManager) trustmanagers[i]);
        }
    }
    sslcontext.init(keymanagers, trustmanagers, null);

    return sslcontext;
}

From source file:it.geosolutions.sfs.web.Start.java

private static boolean keyStoreContainsCertificate(KeyStore ks, String hostname) throws Exception {
    //          SubjectDnX509PrincipalExtractor ex = new SubjectDnX509PrincipalExtractor();
    Enumeration<String> e = ks.aliases();
    while (e.hasMoreElements()) {
        String alias = e.nextElement();
        if (ks.isCertificateEntry(alias)) {
            Certificate c = ks.getCertificate(alias);
            if (c instanceof X509Certificate) {
                X500Principal p = (X500Principal) ((X509Certificate) c).getSubjectX500Principal();
                if (p.getName().contains(hostname))
                    return true;
            }// ww w  .  ja va  2 s .co  m
        }
    }
    return false;
}

From source file:org.glite.slcs.httpclient.ssl.ExtendedX509TrustManager.java

static protected List createTrustedIssuers(KeyStore truststore) throws KeyStoreException {
    List trustedcerts = new ArrayList();
    Enumeration aliases = truststore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = (String) aliases.nextElement();
        Certificate trustedcert = truststore.getCertificate(alias);
        if (trustedcert != null && trustedcert instanceof X509Certificate) {
            X509Certificate cert = (X509Certificate) trustedcert;
            trustedcerts.add(cert);//w  w w  . ja  va 2  s  .c  o m
        }
    }
    return trustedcerts;
}

From source file:com.microsoft.aad.adal4j.AsymmetricKeyCredential.java

/**
 * Static method to create KeyCredential instance.
 * /* w w  w  . ja va  2s . co m*/
 * @param clientId
 *            Identifier of the client requesting the token.
 * @param pkcs12Certificate
 *            PKCS12 certificate stream containing public and private key.
 *            Caller is responsible for handling the input stream.
 * @param password
 *            certificate password
 * @return KeyCredential instance
 * @throws KeyStoreException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 * @throws FileNotFoundException
 * @throws IOException
 * @throws UnrecoverableKeyException
 */
public static AsymmetricKeyCredential create(final String clientId, final InputStream pkcs12Certificate,
        final String password) throws KeyStoreException, NoSuchProviderException, NoSuchAlgorithmException,
        CertificateException, FileNotFoundException, IOException, UnrecoverableKeyException {
    final KeyStore keystore = KeyStore.getInstance("PKCS12", "SunJSSE");
    keystore.load(pkcs12Certificate, password.toCharArray());
    final Enumeration<String> aliases = keystore.aliases();
    final String alias = aliases.nextElement();
    final PrivateKey key = (PrivateKey) keystore.getKey(alias, password.toCharArray());
    final X509Certificate publicCertificate = (X509Certificate) keystore.getCertificate(alias);
    return create(clientId, key, publicCertificate);
}