Example usage for java.security KeyStore getCertificateChain

List of usage examples for java.security KeyStore getCertificateChain

Introduction

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

Prototype

public final Certificate[] getCertificateChain(String alias) throws KeyStoreException 

Source Link

Document

Returns the certificate chain associated with the given alias.

Usage

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    String storename = args[0];/*from  w  w  w  .j  a va  2 s.c  o  m*/
    char[] storepass = args[1].toCharArray();
    String alias = args[2];
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(new FileInputStream(storename), storepass);
    java.security.cert.Certificate[] cchain = ks.getCertificateChain(alias);
    List mylist = new ArrayList();
    for (int i = 0; i < cchain.length; i++) {
        mylist.add(cchain[i]);
    }
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    CertPath cp = cf.generateCertPath(mylist);
    System.out.println(cp);
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    PdfReader reader;//from w w  w.j a  v a 2 s  .  c  o m
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(new FileInputStream(".keystore"), "string".toCharArray());
    PrivateKey key = (PrivateKey) ks.getKey("key", "value".toCharArray());
    Certificate[] chain = ks.getCertificateChain("foobar");
    reader = new PdfReader("2.pdf");
    FileOutputStream os = new FileOutputStream("1.pdf");
    PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
    PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED);
    appearance.setReason("personal");
    appearance.setLocation("Foobar");
    appearance.setVisibleSignature("yoursig");
    stamper.close();
}

From source file:org.wso2.carbon.utils.security.KeyImporter.java

/**
 * sourcekeystore sourceStorepass keyalias targetstore targetStorePass
 *
 * @param args/*from w  w w.j  a va2 s  .  c  o m*/
 */
public static void main(String[] args) throws Exception {

    if (log.isDebugEnabled()) {
        log.debug("Importing certificate ...");
    }

    if (args.length != 5) {
        throw new Exception("Incorrect number of parameters");
    }

    FileOutputStream fileOutputStream = null;

    try {
        String sourceStorePath = args[0];
        String sourceStorePass = args[1];
        String keyAlias = args[2];
        String targetStorePath = args[3];
        String targetStorePass = args[4];

        KeyStore sourceStore = KeyStore.getInstance("JKS");
        FileInputStream fis = new FileInputStream(new File(sourceStorePath).getAbsolutePath());
        sourceStore.load(fis, sourceStorePass.toCharArray());

        Certificate cert = sourceStore.getCertificateChain(keyAlias)[0];
        KeyStore targetStore = KeyStore.getInstance("JKS");

        File targetStoreFile = new File(targetStorePath);
        if (targetStoreFile.exists()) {
            targetStore.load(new FileInputStream(targetStoreFile.getAbsolutePath()),
                    targetStorePass.toCharArray());
        } else {
            targetStore.load(null, null);
        }
        targetStore.setCertificateEntry(keyAlias, cert);
        fileOutputStream = new FileOutputStream(new File(targetStorePath).getAbsolutePath());
        targetStore.store(fileOutputStream, targetStorePass.toCharArray());

        fis.close();
        fileOutputStream.flush();
        if (log.isDebugEnabled()) {
            log.debug("Importing certificate ... DONE !");
        }
    } catch (Exception e) {
        log.error("Importing of key failed");
        throw e;

    } finally {
        if (fileOutputStream != null) {
            fileOutputStream.close();
        }
    }
}

From source file:PKCS12Import.java

public static void main(String[] args) throws Exception {
    if (args.length < 1) {
        System.err.println("usage: java PKCS12Import {pkcs12file} [newjksfile]");
        System.exit(1);/*from w ww.java  2 s  . c  o  m*/
    }

    File fileIn = new File(args[0]);
    File fileOut;
    if (args.length > 1) {
        fileOut = new File(args[1]);
    } else {
        fileOut = new File("newstore.jks");
    }

    if (!fileIn.canRead()) {
        System.err.println("Unable to access input keystore: " + fileIn.getPath());
        System.exit(2);
    }

    if (fileOut.exists() && !fileOut.canWrite()) {
        System.err.println("Output file is not writable: " + fileOut.getPath());
        System.exit(2);
    }

    KeyStore kspkcs12 = KeyStore.getInstance("pkcs12");
    KeyStore ksjks = KeyStore.getInstance("jks");

    System.out.print("Enter input keystore passphrase: ");
    char[] inphrase = readPassphrase();
    System.out.print("Enter output keystore passphrase: ");
    char[] outphrase = readPassphrase();

    kspkcs12.load(new FileInputStream(fileIn), inphrase);

    ksjks.load((fileOut.exists()) ? new FileInputStream(fileOut) : null, outphrase);

    Enumeration eAliases = kspkcs12.aliases();
    int n = 0;
    while (eAliases.hasMoreElements()) {
        String strAlias = (String) eAliases.nextElement();
        System.err.println("Alias " + n++ + ": " + strAlias);

        if (kspkcs12.isKeyEntry(strAlias)) {
            System.err.println("Adding key for alias " + strAlias);
            Key key = kspkcs12.getKey(strAlias, inphrase);

            Certificate[] chain = kspkcs12.getCertificateChain(strAlias);

            ksjks.setKeyEntry(strAlias, key, outphrase, chain);
        }
    }

    OutputStream out = new FileOutputStream(fileOut);
    ksjks.store(out, outphrase);
    out.close();
}

From source file:org.openhealthtools.openatna.net.ConnectionCertificateHandler.java

/**
 * For debuging only.  Prints out keystore certificate chain.
 *
 * @param keystore Keystore to print out.
 * @throws KeyStoreException If the keystore is broken.
 *///from   w ww  . jav a 2  s  . c o  m
public static void printKeyCertificates(KeyStore keystore) throws KeyStoreException {
    Enumeration<String> aliases = keystore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        Certificate[] certs = keystore.getCertificateChain(alias);
        if (certs != null) {
            String message = "Certificate chain '" + alias + "':";
            int i = 1;
            for (Certificate cert : certs) {
                if (cert instanceof X509Certificate) {
                    X509Certificate Xcert = (X509Certificate) cert;
                    message += "\n Certificate " + i++ + ":";
                    message += "\n  Subject DN: " + Xcert.getSubjectDN();
                    message += "\n  Signature Algorithm: " + Xcert.getSigAlgName();
                    message += "\n  Valid from: " + Xcert.getNotBefore();
                    message += "\n  Valid until: " + Xcert.getNotAfter();
                    message += "\n  Issuer: " + Xcert.getIssuerDN();
                }
            }
            log.info(message);
        }
    }
}

From source file:org.wso2.carbon.identity.user.store.configuration.deployer.util.UserStoreUtil.java

public static Cipher getCipherOfSuperTenant() throws UserStoreException {
    Cipher cipher;/*  w w w.j  ava 2  s .  com*/
    ServerConfigurationService config = UserStoreConfigComponent.getServerConfigurationService();

    if (config == null) {
        String errMsg = "ServerConfigurationService is null - this situation can't occur";
        throw new UserStoreException(errMsg);
    }

    String filePath = config.getFirstProperty(UserStoreConfigurationConstants.SERVER_KEYSTORE_FILE);
    String keyStoreType = config.getFirstProperty(UserStoreConfigurationConstants.SERVER_KEYSTORE_TYPE);
    String password = config.getFirstProperty(UserStoreConfigurationConstants.SERVER_KEYSTORE_PASSWORD);
    String keyAlias = config.getFirstProperty(UserStoreConfigurationConstants.SERVER_KEYSTORE_KEY_ALIAS);

    KeyStore store;
    InputStream inputStream = null;

    try {
        inputStream = new FileInputStream(new File(filePath).getAbsolutePath());
        store = KeyStore.getInstance(keyStoreType);
        store.load(inputStream, password.toCharArray());
        Certificate[] certs = store.getCertificateChain(keyAlias);
        cipher = Cipher.getInstance("RSA", "BC");
        cipher.init(Cipher.ENCRYPT_MODE, certs[0].getPublicKey());
    } catch (FileNotFoundException e) {
        String errorMsg = "Keystore File Not Found in configured location";
        throw new UserStoreException(errorMsg, e);
    } catch (IOException e) {
        String errorMsg = "Keystore File IO operation failed";
        throw new UserStoreException(errorMsg, e);
    } catch (InvalidKeyException e) {
        String errorMsg = "Invalid key is used to access keystore";
        throw new UserStoreException(errorMsg, e);
    } catch (KeyStoreException e) {
        String errorMsg = "Faulty keystore";
        throw new UserStoreException(errorMsg, e);
    } catch (GeneralSecurityException e) {
        String errorMsg = "Some parameters assigned to access the " + "keystore is invalid";
        throw new UserStoreException(errorMsg, e);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                log.error("Key store file closing failed");
            }
        }
    }
    return cipher;
}

From source file:org.wso2.carbon.identity.sso.saml.TestUtils.java

public static void prepareCredentials(X509Credential x509Credential)
        throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException {

    KeyStore keyStore = TestUtils.loadKeyStoreFromFileSystem(
            TestUtils.getFilePath(TestConstants.KEY_STORE_NAME), TestConstants.WSO2_CARBON, "JKS");
    X509Certificate[] issuerCerts = null;
    Certificate[] certificates;//w ww. ja va 2 s. c  o m

    certificates = keyStore.getCertificateChain(TestConstants.WSO2_CARBON);
    issuerCerts = new X509Certificate[certificates.length];

    int i = 0;
    for (Certificate certificate : certificates) {
        issuerCerts[i++] = (X509Certificate) certificate;
    }
    when(x509Credential.getEntityCertificate()).thenReturn((X509Certificate) certificates[0]);
    when(x509Credential.getEntityCertificateChain()).thenReturn(Arrays.asList(issuerCerts));
    when(x509Credential.getPrivateKey()).thenReturn(
            (PrivateKey) keyStore.getKey(TestConstants.WSO2_CARBON, TestConstants.WSO2_CARBON.toCharArray()));
    when(x509Credential.getPublicKey()).thenReturn(issuerCerts[0].getPublicKey());
}

From source file:org.wso2.carbon.identity.user.store.configuration.utils.SecondaryUserStoreConfigurationUtil.java

/**
 * Initializes the key store and assign it to Cipher object.
 *
 * @throws IdentityUserStoreMgtException Cipher object creation failed
 *///from   ww  w  .j a  v  a2 s. c  om
private static void initializeKeyStore() throws IdentityUserStoreMgtException {

    if (cipher == null) {
        ServerConfigurationService config = UserStoreConfigComponent.getServerConfigurationService();

        if (config != null) {
            String filePath = config.getFirstProperty(SERVER_KEYSTORE_FILE);
            String keyStoreType = config.getFirstProperty(SERVER_KEYSTORE_TYPE);
            String password = config.getFirstProperty(SERVER_KEYSTORE_PASSWORD);
            String keyAlias = config.getFirstProperty(SERVER_KEYSTORE_KEY_ALIAS);

            KeyStore store;
            InputStream inputStream = null;

            try {
                inputStream = new FileInputStream(new File(filePath).getAbsolutePath());
                store = KeyStore.getInstance(keyStoreType);
                store.load(inputStream, password.toCharArray());
                Certificate[] certs = store.getCertificateChain(keyAlias);
                cipher = Cipher.getInstance("RSA", "BC");
                cipher.init(Cipher.ENCRYPT_MODE, certs[0].getPublicKey());
            } catch (FileNotFoundException e) {
                String errorMsg = "Keystore File Not Found in configured location";
                throw new IdentityUserStoreMgtException(errorMsg, e);
            } catch (IOException e) {
                String errorMsg = "Keystore File IO operation failed";
                throw new IdentityUserStoreMgtException(errorMsg, e);
            } catch (InvalidKeyException e) {
                String errorMsg = "Invalid key is used to access keystore";
                throw new IdentityUserStoreMgtException(errorMsg, e);
            } catch (KeyStoreException e) {
                String errorMsg = "Faulty keystore";
                throw new IdentityUserStoreMgtException(errorMsg, e);
            } catch (GeneralSecurityException e) {
                String errorMsg = "Some parameters assigned to access the " + "keystore is invalid";
                throw new IdentityUserStoreMgtException(errorMsg, e);
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        log.error("Exception occurred while trying to close the keystore " + "file", e);
                    }
                }
            }
        } else {
            String errMsg = "ServerConfigurationService is null - this situation can't occur";
            log.error(errMsg);
        }

    }
}

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

@SuppressWarnings("unused")
private static void loadWindowsCert() throws Exception {
    KeyStore ks = KeyStore.getInstance("Windows-MY");// "Windows-ROOT"
    ks.load(null, null);//w  w w. j av a 2  s  .co  m
    Enumeration<String> en = ks.aliases();
    while (en.hasMoreElements()) {
        String key = en.nextElement();
        Certificate[] certs = ks.getCertificateChain(key);
        X509Certificate cert = (X509Certificate) certs[0];
    }
}

From source file:org.roda.common.certification.PDFSignatureUtils.java

public static Path runDigitalSignatureSign(Path input, String keystore, String alias, String password,
        String reason, String location, String contact)
        throws IOException, GeneralSecurityException, DocumentException {

    Security.addProvider(new BouncyCastleProvider());
    Path signedPDF = Files.createTempFile("signed", ".pdf");

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    InputStream is = new FileInputStream(keystore);
    ks.load(is, password.toCharArray());
    PrivateKey pk = (PrivateKey) ks.getKey(alias, password.toCharArray());
    Certificate[] chain = ks.getCertificateChain(alias);
    IOUtils.closeQuietly(is);/*w ww .  j  a va2s  . co  m*/

    PdfReader reader = new PdfReader(input.toString());
    FileOutputStream os = new FileOutputStream(signedPDF.toFile());
    PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
    PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setReason(reason);
    appearance.setLocation(location);
    appearance.setContact(contact);
    appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "RODASignature");
    ExternalDigest digest = new BouncyCastleDigest();
    ExternalSignature signature = new PrivateKeySignature(pk, DigestAlgorithms.SHA256, "BC");
    MakeSignature.signDetached(appearance, digest, signature, chain, null, null, null, 0, null);
    IOUtils.closeQuietly(os);
    reader.close();

    return signedPDF;
}