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

public static void main(String[] args) throws Exception {
    String keystoreFilename = "my.keystore";

    char[] password = "password".toCharArray();
    String alias = "alias";

    FileInputStream fIn = new FileInputStream(keystoreFilename);
    KeyStore keystore = KeyStore.getInstance("JKS");

    keystore.load(fIn, password);/*  w w  w.  ja  v  a  2 s .  c  o m*/

    Certificate cert = keystore.getCertificate(alias);

    System.out.println(cert);
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    FileInputStream is = new FileInputStream("your.keystore");

    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(is, "my-keystore-password".toCharArray());

    // Get certificate
    java.security.cert.Certificate cert = keystore.getCertificate("myalias");
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    FileInputStream is = new FileInputStream("your.keystore");

    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(is, "my-keystore-password".toCharArray());

    String alias = "myalias";
    Certificate cert = keystore.getCertificate(alias);

    CertificateFactory certFact = CertificateFactory.getInstance("X.509");
    CertPath path = certFact.generateCertPath(Arrays.asList(new Certificate[] { cert }));

}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    FileInputStream is = new FileInputStream("your.keystore");

    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(is, "my-keystore-password".toCharArray());

    String alias = "myalias";
    Certificate cert = keystore.getCertificate(alias);

    File file = null;//from   w w  w  . j av a2  s.c o m
    byte[] buf = cert.getEncoded();

    FileOutputStream os = new FileOutputStream(file);
    os.write(buf);
    os.close();

    Writer wr = new OutputStreamWriter(os, Charset.forName("UTF-8"));
    wr.write(new sun.misc.BASE64Encoder().encode(buf));
    wr.flush();

}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    String keystoreFile = "keyStoreFile.bin";
    String caAlias = "caAlias";
    String certToSignAlias = "cert";
    String newAlias = "newAlias";

    char[] password = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' };
    char[] caPassword = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' };
    char[] certPassword = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' };

    FileInputStream input = new FileInputStream(keystoreFile);
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(input, password);/*from  w  ww .j  a v a2  s  . c o m*/
    input.close();

    PrivateKey caPrivateKey = (PrivateKey) keyStore.getKey(caAlias, caPassword);
    java.security.cert.Certificate caCert = keyStore.getCertificate(caAlias);

    byte[] encoded = caCert.getEncoded();
    X509CertImpl caCertImpl = new X509CertImpl(encoded);

    X509CertInfo caCertInfo = (X509CertInfo) caCertImpl.get(X509CertImpl.NAME + "." + X509CertImpl.INFO);

    X500Name issuer = (X500Name) caCertInfo.get(X509CertInfo.SUBJECT + "." + CertificateIssuerName.DN_NAME);

    java.security.cert.Certificate cert = keyStore.getCertificate(certToSignAlias);
    PrivateKey privateKey = (PrivateKey) keyStore.getKey(certToSignAlias, certPassword);
    encoded = cert.getEncoded();
    X509CertImpl certImpl = new X509CertImpl(encoded);
    X509CertInfo certInfo = (X509CertInfo) certImpl.get(X509CertImpl.NAME + "." + X509CertImpl.INFO);

    Date firstDate = new Date();
    Date lastDate = new Date(firstDate.getTime() + 365 * 24 * 60 * 60 * 1000L);
    CertificateValidity interval = new CertificateValidity(firstDate, lastDate);

    certInfo.set(X509CertInfo.VALIDITY, interval);

    certInfo.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber((int) (firstDate.getTime() / 1000)));

    certInfo.set(X509CertInfo.ISSUER + "." + CertificateSubjectName.DN_NAME, issuer);

    AlgorithmId algorithm = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid);
    certInfo.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, algorithm);
    X509CertImpl newCert = new X509CertImpl(certInfo);

    newCert.sign(caPrivateKey, "MD5WithRSA");

    keyStore.setKeyEntry(newAlias, privateKey, certPassword, new java.security.cert.Certificate[] { newCert });

    FileOutputStream output = new FileOutputStream(keystoreFile);
    keyStore.store(output, password);
    output.close();

}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    FileInputStream is = new FileInputStream("your.keystore");

    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(is, "my-keystore-password".toCharArray());

    Enumeration e = keystore.aliases();
    for (; e.hasMoreElements();) {
        String alias = (String) e.nextElement();

        java.security.cert.Certificate cert = keystore.getCertificate(alias);
        if (cert instanceof X509Certificate) {
            X509Certificate x509cert = (X509Certificate) cert;

            // Get subject
            Principal principal = x509cert.getSubjectDN();
            String subjectDn = principal.getName();

            // Get issuer
            principal = x509cert.getIssuerDN();
            String issuerDn = principal.getName();
        }//from www .  jav a  2s .c  o m
    }
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    FileInputStream is = new FileInputStream("your.keystore");

    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(is, "my-keystore-password".toCharArray());

    String alias = "myalias";

    Key key = keystore.getKey(alias, "password".toCharArray());
    if (key instanceof PrivateKey) {
        // Get certificate of public key
        Certificate cert = keystore.getCertificate(alias);

        // Get public key
        PublicKey publicKey = cert.getPublicKey();

        // Return a key pair
        new KeyPair(publicKey, (PrivateKey) key);
    }/* w ww. j  a v  a  2s .co m*/
}

From source file:com.gsma.iariauth.validator.util.IARIValidatorMain.java

public static void main(String[] args) {
    String formatstr = "IARIValidator [-d <authorization document>] [-n <package name>] [-ps <package signer fingerprint>] [-pk <package signer keystore>] [-pa <package signer certificate alias>] [-pp <package signer keystore password>] -k <keystore> -p <password> [-v]";

    HelpFormatter formatter = new HelpFormatter();
    GnuParser parser = new GnuParser();
    Options opts = new Options();

    opts.addOption(new ArgOption("d", "document", "IARI Authorization document"));
    opts.addOption(new ArgOption("pkgname", "package-name", "package name"));
    opts.addOption(new ArgOption("pkgsigner", "package-signer", "package signer fingerprint"));
    opts.addOption(new ArgOption("pkgkeystore", "package-keystore", "package signing keystore"));
    opts.addOption(new ArgOption("pkgalias", "package-key-alias", "package signing certificate alias"));
    opts.addOption(new ArgOption("pkgstorepass", "package-keystore-pass", "package signing keystore password"));
    opts.addOption(new Option("v", "verbose", false, "verbose output"));

    CommandLine cli = null;/*ww  w. j  a va2s  .c o m*/
    try {
        cli = parser.parse(opts, args);
    } catch (ParseException e) {
        formatter.printHelp(formatstr, opts);
        return;
    }

    boolean verbose = cli.hasOption("v");

    String packageName = cli.getOptionValue("pkgname");
    String packageSigner = cli.getOptionValue("pkgsigner");
    if (packageSigner == null) {
        String packageSignerKeystore = cli.getOptionValue("pkgkeystore");
        String packageSignerKeystoreAlias = cli.getOptionValue("pkgalias");
        String packageSignerKeystorePasswd = cli.getOptionValue("pkgstorepass");
        if (packageSignerKeystore != null) {
            if (packageSignerKeystoreAlias == null) {
                System.err.println("No alias given for package signing certificate");
                System.exit(1);
            }
            if (packageSignerKeystorePasswd == null) {
                System.err.println("No password given for package signing keystore");
                System.exit(1);
            }
            KeyStore packageKeystore = loadKeyStore(packageSignerKeystore, packageSignerKeystorePasswd);
            if (packageKeystore == null) {
                System.err.println("Unable to read package keystore");
                System.exit(1);
            }
            try {
                X509Certificate c = (X509Certificate) packageKeystore
                        .getCertificate(packageSignerKeystoreAlias);
                if (c == null) {
                    System.err.println("Unable to access package signing certificate");
                    System.exit(1);
                }
                packageSigner = getFingerprint(c);
            } catch (KeyStoreException e) {
                System.err.println("Unable to access package signing certificate");
                System.exit(1);
            } catch (CertificateEncodingException e) {
                e.printStackTrace();
                System.err.println("Unable to read package signing certificate");
                System.exit(1);
            }
        }
    }

    String authDocumentPath = cli.getOptionValue("d");
    if (authDocumentPath == null) {
        System.err.println("No auth document specified");
        System.exit(1);
    }
    File authDocument = new File(authDocumentPath);
    if (!authDocument.exists() || !authDocument.isFile()) {
        System.err.println("Unable to read specified auth document");
        System.exit(1);
    }

    PackageProcessor processor = new PackageProcessor(packageName, packageSigner);
    ProcessingResult result = processor.processIARIauthorization(authDocument);
    if (result.getStatus() != ProcessingResult.STATUS_OK) {
        System.err.println("Error validating authDocument:");
        System.err.println(result.getError().toString());
        System.exit(1);
    }

    if (verbose) {
        System.out.println(result.getAuthDocument().toString());
    }
    System.exit(0);
}

From source file:com.daon.identityx.utils.GenerateAndroidFacet.java

public static void main(String[] args) {

    String androidKeystoreLocation = System.getProperty("ANDROID_KEYSTORE_LOCATION",
            DEFAULT_ANDROID_KEYSTORE_LOCATION);
    String androidKeystorePassword = System.getProperty("ANDROID_KEYSTORE_PASSWORD",
            DEFAULT_ANDROID_KEYSTORE_PASSWORD);
    String androidKeystoreCert = System.getProperty("ANDROID_KEYSTORE_CERT_NAME",
            DEFAULT_ANDROID_KEYSTORE_CERT_NAME);
    String hashingAlgorithm = System.getProperty("HASHING_ALGORITHM", DEFAULT_HASHING_ALGORITHM);

    try {// ww w . ja  v  a2s  .c o m
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        File filePath = new File(androidKeystoreLocation);
        if (!filePath.exists()) {
            System.err.println(
                    "The filepath to the debug keystore could not be located at: " + androidKeystoreCert);
            System.exit(1);
        } else {
            System.out.println("Found the Android Studio keystore at: " + androidKeystoreLocation);
        }

        keyStore.load(new FileInputStream(filePath), androidKeystorePassword.toCharArray());
        System.out.println("Keystore loaded - password and location were OK");

        Certificate cert = keyStore.getCertificate(androidKeystoreCert);
        if (cert == null) {
            System.err.println(
                    "Could not location the certification in the store with the name: " + androidKeystoreCert);
            System.exit(1);
        } else {
            System.out.println("Certificate found in the store with name: " + androidKeystoreCert);
        }

        byte[] certBytes = cert.getEncoded();

        MessageDigest digest = MessageDigest.getInstance(hashingAlgorithm);
        System.out.println("Hashing algorithm: " + hashingAlgorithm + " found.");
        byte[] hashedCert = digest.digest(certBytes);
        String base64HashedCert = Base64.getEncoder().encodeToString(hashedCert);
        System.out.println("Base64 encoded SHA-1 hash of the certificate: " + base64HashedCert);
        String base64HashedCertRemoveTrailing = StringUtils.deleteAny(base64HashedCert, "=");
        System.out.println(
                "Add the following facet to the Facets file in order for the debug app to be trusted by the FIDO client");
        System.out.println("\"android:apk-key-hash:" + base64HashedCertRemoveTrailing + "\"");

    } catch (Throwable ex) {
        ex.printStackTrace();
    }

}

From source file:com.peterphi.std.crypto.keygen.CaHelper.java

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

    String casubject = "C=UK, O=SOMEORG, OU=Org Unit, CN=Example Certificate Authority";

    X509Certificate cacert = null;
    PrivateKey caPrivateKey = null;

    if (true) {/* ww w  .j  ava  2  s. co  m*/
        KeyStore ks = KeyStore.getInstance("PKCS12", "BC");

        ks.load(new FileInputStream(new File("/tmp/someorg-ca.p12")), new char[] {});
        caPrivateKey = (PrivateKey) ks.getKey("ca", new char[] {});

        cacert = (X509Certificate) ks.getCertificate("ca");
    } else {
        KeyPair cakeys = generateKeyPair(2048);
        caPrivateKey = cakeys.getPrivate();
        cacert = generateCaCertificate(casubject, cakeys, (BigInteger) null, new X509Name(casubject));
    }

    {
        // CA .p12
        {
            KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
            ks.load(null);
            //ks.setCertificateEntry("ca", cacert);
            ks.setKeyEntry("ca", caPrivateKey, new char[] {}, new java.security.cert.Certificate[] { cacert });

            ks.store(new FileOutputStream("/tmp/someorg-ca.p12"), new char[] {});
        }

        // CA .jks (public key only)
        {
            KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(null);
            ks.setCertificateEntry("ca", cacert);

            ks.store(new FileOutputStream("/tmp/ca-public.jks"), new char[] {});
        }

        // CA .pem (public key only)
        {
            PEMWriter pem = new PEMWriter(new FileWriter(new File("/tmp/d3ca.crt")));

            pem.writeObject(cacert);
            pem.close();
        }
    }

    /*
    // User
    {
       String user = "C=UK, O=SOMEORG, OU=Org Unit, L=SomeCompany, CN=Some User (test)";
       KeyPair keys = generateKeyPair(1024);
       X509Certificate cert = generateClientCertificate(keys.getPublic(), caPrivateKey, new X509Name(subject),
     new X509Name(user));
            
       {
    KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
    ks.load(null);
    ks.setCertificateEntry("issuer", cacert);
    ks.setCertificateEntry("me", cert);
    ks.setKeyEntry("me", keys.getPrivate(), new char[] {}, new java.security.cert.Certificate[] { cert, cacert });
            
    ks.store(new FileOutputStream("/tmp/someorg-someuser.p12"), "SomeCompanysecurity".toCharArray());
       }
            
       {
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null);
    ks.setKeyEntry("me", keys.getPrivate(), new char[] {}, new java.security.cert.Certificate[] { cert, cacert });
    // ks.setCertificateEntry("issuer", cacert);
    // ks.setCertificateEntry("me", cert);
            
    ks.store(new FileOutputStream("/tmp/someorg-someuser.jks"), new char[] {});
       }
    }//*/

    // examplehost hostkey:
    {
        String user = "C=UK, O=SOMEORG, OU=Org Unit, L=SomeCompany, CN=examplehost.example.com";
        KeyPair keys = generateKeyPair(1024);
        X509Certificate cert = generateServerCertificate(keys.getPublic(), caPrivateKey,
                new X509Name(casubject), new X509Name(user));

        {
            KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(null);
            ks.setKeyEntry("me", keys.getPrivate(), new char[] {},
                    new java.security.cert.Certificate[] { cert, cacert });
            // ks.setCertificateEntry("issuer", cacert);
            // ks.setCertificateEntry("me", cert);

            ks.store(new FileOutputStream("/tmp/host.jks"), new char[] {});
        }

        {
            KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
            ks.load(null);
            ks.setCertificateEntry("issuer", cacert);
            ks.setCertificateEntry("me", cert);
            ks.setKeyEntry("me", keys.getPrivate(), new char[] {},
                    new java.security.cert.Certificate[] { cert, cacert });

            ks.store(new FileOutputStream("/tmp/host.p12"), new char[] {});
        }
    }
}