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:gov.nih.nci.cacisweb.action.SecureXDSNAVAction.java

@Override
public String input() throws Exception {
    log.debug("input() - START");
    secureXDSNAVRecepientList = new ArrayList<SecureXDSNAVModel>();

    String secureXDSNAVKeystoreLocation = CaCISUtil
            .getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECXDSNAV_RECEPIENT_TRUSTSTORE_LOCATION);
    String secureXDSNAVKeystorePassword = CaCISUtil
            .getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECXDSNAV_RECEPIENT_TRUSTSTORE_PASSWORD);
    String propertyFileLocation = CaCISUtil
            .getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECXDSNAV_RECEPIENT_CONFIG_FILE_LOCATION);

    CaCISUtil caCISUtil = new CaCISUtil();
    try {/*from   w  w w.  j  a  v a2s .  com*/
        caCISUtil.isPropertyFileAndKeystoreInSync(propertyFileLocation, secureXDSNAVKeystoreLocation,
                CaCISWebConstants.COM_KEYSTORE_TYPE_JKS, secureXDSNAVKeystorePassword);
    } catch (PropFileAndKeystoreOutOfSyncException e) {
        log.error(e.getMessage());
        addActionError(e.getMessage());
    }

    try {
        KeyStore keystore = caCISUtil.getKeystore(secureXDSNAVKeystoreLocation,
                CaCISWebConstants.COM_KEYSTORE_TYPE_JKS, secureXDSNAVKeystorePassword);
        // List the aliases
        //            Enumeration<String> enumeration = keystore.aliases();            
        Properties configFile = new Properties();
        InputStream is = new FileInputStream(propertyFileLocation);
        configFile.load(is);
        is.close();
        Enumeration<Object> enumeration = configFile.keys();
        //            while (enumeration.hasMoreElements()) {
        //                String alias = (String) enumeration.nextElement();
        //                X509Certificate x509Certificate = (X509Certificate) keystore.getCertificate(alias);
        //                SecureXDSNAVModel secureXDSNAVModel = new SecureXDSNAVModel();
        //                secureXDSNAVModel.setCertificateAlias(alias);
        //                secureXDSNAVModel.setCertificateDN(x509Certificate.getSubjectDN().toString());
        //                secureXDSNAVRecepientList.add(secureXDSNAVModel);
        //                log.debug("Alias: " + alias + " DN: " + x509Certificate.getSubjectDN().getName());
        //            }            
        while (enumeration.hasMoreElements()) {
            String alias = (String) enumeration.nextElement();
            X509Certificate x509Certificate = (X509Certificate) keystore.getCertificate(alias);
            String distinguishedName = "";
            if (x509Certificate != null) {
                distinguishedName = x509Certificate.getSubjectDN().toString();
            }
            //              String distinguishedName = CaCISUtil.getPropertyFromPropertiesFile(propertyFileLocation, alias);
            SecureXDSNAVModel secureXDSNAVModel = new SecureXDSNAVModel();
            secureXDSNAVModel.setCertificateAlias(alias);
            secureXDSNAVModel.setCertificateDN(distinguishedName);
            secureXDSNAVRecepientList.add(secureXDSNAVModel);
            log.debug("Alias: " + alias + " DN: " + distinguishedName);
        }

        caCISUtil.releaseKeystore();
    } catch (KeystoreInstantiationException kie) {
        log.error(kie.getMessage());
        addActionError(getText("exception.keystoreInstantiation"));
        return ERROR;
    }
    log.debug("input() - END");
    return INPUT;
}

From source file:org.apache.ws.security.components.crypto.Merlin.java

/**
 * Get an X509 Certificate (chain) of the X500Principal argument in the supplied KeyStore 
 * @param subjectRDN either an X500Principal or a BouncyCastle X509Name instance.
 * @param store The KeyStore/*from   ww w . j av a  2  s.  co  m*/
 * @return an X509 Certificate (chain)
 * @throws WSSecurityException
 */
private Certificate[] getCertificates(byte[] skiBytes, KeyStore store) throws WSSecurityException {
    try {
        for (Enumeration<String> e = store.aliases(); e.hasMoreElements();) {
            String alias = e.nextElement();
            Certificate cert = null;
            Certificate[] certs = store.getCertificateChain(alias);
            if (certs == null || certs.length == 0) {
                // no cert chain, so lets check if getCertificate gives us a result.
                cert = store.getCertificate(alias);
                if (cert == null) {
                    continue;
                }
                certs = new Certificate[] { cert };
            } else {
                cert = certs[0];
            }
            if (cert instanceof X509Certificate) {
                X509Certificate x509cert = (X509Certificate) cert;
                byte[] data = getSKIBytesFromCert(x509cert);
                if (data.length == skiBytes.length && Arrays.equals(data, skiBytes)) {
                    return certs;
                }
            }
        }
    } catch (KeyStoreException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "keystore", null, e);
    }
    return new Certificate[] {};
}

From source file:org.apache.ws.security.components.crypto.Merlin.java

/**
 * Get an X509 Certificate (chain) of the X500Principal argument in the supplied KeyStore 
 * @param subjectRDN either an X500Principal or a BouncyCastle X509Name instance.
 * @param store The KeyStore/*ww  w .ja  v a2 s.c  o m*/
 * @return an X509 Certificate (chain)
 * @throws WSSecurityException
 */
private Certificate[] getCertificates(Object subjectRDN, KeyStore store) throws WSSecurityException {
    try {
        for (Enumeration<String> e = store.aliases(); e.hasMoreElements();) {
            String alias = e.nextElement();
            Certificate cert = null;
            Certificate[] certs = store.getCertificateChain(alias);
            if (certs == null || certs.length == 0) {
                // no cert chain, so lets check if getCertificate gives us a result.
                cert = store.getCertificate(alias);
                if (cert == null) {
                    continue;
                }
                certs = new Certificate[] { cert };
            } else {
                cert = certs[0];
            }
            if (cert instanceof X509Certificate) {
                X500Principal foundRDN = ((X509Certificate) cert).getSubjectX500Principal();
                Object certName = createBCX509Name(foundRDN.getName());

                if (subjectRDN.equals(certName)) {
                    return certs;
                }
            }
        }
    } catch (KeyStoreException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "keystore", null, e);
    }
    return new Certificate[] {};
}

From source file:org.apache.ws.security.components.crypto.Merlin.java

/**
 * Get an X509 Certificate (chain) of the X500Principal argument in the supplied KeyStore 
 * @param subjectRDN either an X500Principal or a BouncyCastle X509Name instance.
 * @param store The KeyStore//from   w  ww  . j a va2s.c  o m
 * @return an X509 Certificate (chain)
 * @throws WSSecurityException
 */
private Certificate[] getCertificates(Object issuerRDN, BigInteger serialNumber, KeyStore store)
        throws WSSecurityException {
    try {
        for (Enumeration<String> e = store.aliases(); e.hasMoreElements();) {
            String alias = e.nextElement();
            Certificate cert = null;
            Certificate[] certs = store.getCertificateChain(alias);
            if (certs == null || certs.length == 0) {
                // no cert chain, so lets check if getCertificate gives us a result.
                cert = store.getCertificate(alias);
                if (cert == null) {
                    continue;
                }
                certs = new Certificate[] { cert };
            } else {
                cert = certs[0];
            }
            if (cert instanceof X509Certificate) {
                X509Certificate x509cert = (X509Certificate) cert;
                if (x509cert.getSerialNumber().compareTo(serialNumber) == 0) {
                    Object certName = createBCX509Name(x509cert.getIssuerX500Principal().getName());
                    if (certName.equals(issuerRDN)) {
                        return certs;
                    }
                }
            }
        }
    } catch (KeyStoreException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "keystore", null, e);
    }
    return new Certificate[] {};
}

From source file:org.apache.ws.security.components.crypto.Merlin.java

/**
 * Get an implementation-specific identifier that corresponds to the X509Certificate. In
 * this case, the identifier is the KeyStore alias.
 * @param cert The X509Certificate corresponding to the returned identifier
 * @param store The KeyStore to search/* w  w w . ja  v  a 2s.  co m*/
 * @return An implementation-specific identifier that corresponds to the X509Certificate
 */
private String getIdentifier(X509Certificate cert, KeyStore store) throws WSSecurityException {
    try {
        for (Enumeration<String> e = store.aliases(); e.hasMoreElements();) {
            String alias = e.nextElement();

            Certificate[] certs = store.getCertificateChain(alias);
            Certificate retrievedCert = null;
            if (certs == null || certs.length == 0) {
                // no cert chain, so lets check if getCertificate gives us a  result.
                retrievedCert = store.getCertificate(alias);
                if (retrievedCert == null) {
                    continue;
                }
            } else {
                retrievedCert = certs[0];
            }
            if (!(retrievedCert instanceof X509Certificate)) {
                continue;
            }
            if (retrievedCert.equals(cert)) {
                return alias;
            }
        }
    } catch (KeyStoreException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "keystore", null, e);
    }
    return null;
}

From source file:com.qut.middleware.esoemanager.manager.logic.impl.ServiceCryptoImpl.java

public void createServiceKey(String serviceID) throws ServiceCryptoCreationException {
    String keyStorePassphrase;//w  ww  .j  av a  2s .  co m
    String keyPairName;
    String keyPairPassphrase;
    String keyPairSubjectDN;
    KeyPair spKeyPair;
    KeyStore keyStore;
    byte[] keyStoreBytes;

    try {
        Integer entID = new Integer(serviceID);

        if (entID.intValue() == this.esoeENTID) {
            keyPairSubjectDN = this.generateSubjectDN(this.esoeEntityID);
        } else {
            String serviceURL = null;
            Map<String, Object> description = this.managerDAO.queryServiceDescription(entID);
            if (description == null)
                throw new ServiceCryptoCreationException("Unable to retrieve serviceURL for this service");

            serviceURL = (String) description.get(Constants.FIELD_SERVICE_URL);
            keyPairSubjectDN = this.generateSubjectDN(serviceURL);
        }

        keyPairName = this.identifierGenerator.generateXMLKeyName();

        keyStorePassphrase = this.generatePassphrase();
        keyPairPassphrase = this.generatePassphrase();

        keyStore = this.cryptoProcessor.generateKeyStore();
        spKeyPair = this.cryptoProcessor.generateKeyPair();
        this.cryptoProcessor.addKeyPair(keyStore, keyStorePassphrase, spKeyPair, keyPairName, keyPairPassphrase,
                keyPairSubjectDN);
        keyStoreBytes = this.cryptoProcessor.convertKeystoreByteArray(keyStore, keyStorePassphrase);

        X509Certificate certificate = (X509Certificate) keyStore.getCertificate(keyPairName);

        /* Determine expiry date of PKI data */
        Calendar expiryDate = Calendar.getInstance();
        expiryDate.add(Calendar.YEAR, this.cryptoProcessor.getCertExpiryIntervalInYears());

        if (entID.intValue() == this.esoeENTID) {
            /** Commit key data to IDP reference */
            Integer descID_IDP = this.managerDAO.getDescID(entID, Constants.IDP_DESCRIPTOR);
            this.managerDAO.insertPublicKey(descID_IDP, expiryDate.getTime(), keyPairName,
                    this.cryptoProcessor.getCertIssuerDN(), certificate.getSerialNumber().toString(),
                    this.cryptoProcessor.convertPublicKeyByteArray(spKeyPair.getPublic()));

            this.managerDAO.insertPKIData(descID_IDP, expiryDate.getTime(), keyStoreBytes, keyStorePassphrase,
                    keyPairName, keyPairPassphrase);

            /** Commit key data to PDP reference */
            Integer descID_PDP = this.managerDAO.getDescID(entID, Constants.LXACML_PDP_DESCRIPTOR);
            this.managerDAO.insertPublicKey(descID_PDP, expiryDate.getTime(), keyPairName,
                    this.cryptoProcessor.getCertIssuerDN(), certificate.getSerialNumber().toString(),
                    this.cryptoProcessor.convertPublicKeyByteArray(spKeyPair.getPublic()));

            this.managerDAO.insertPKIData(descID_PDP, expiryDate.getTime(), keyStoreBytes, keyStorePassphrase,
                    keyPairName, keyPairPassphrase);

            /** Commit key data to Attribute Authority reference */
            Integer descID_AA = this.managerDAO.getDescID(entID, Constants.ATTRIBUTE_AUTHORITY_DESCRIPTOR);
            this.managerDAO.insertPublicKey(descID_AA, expiryDate.getTime(), keyPairName,
                    this.cryptoProcessor.getCertIssuerDN(), certificate.getSerialNumber().toString(),
                    this.cryptoProcessor.convertPublicKeyByteArray(spKeyPair.getPublic()));

            this.managerDAO.insertPKIData(descID_AA, expiryDate.getTime(), keyStoreBytes, keyStorePassphrase,
                    keyPairName, keyPairPassphrase);
        } else {
            Integer descID = this.managerDAO.getDescID(entID, Constants.SP_DESCRIPTOR);
            this.managerDAO.insertPublicKey(descID, expiryDate.getTime(), keyPairName,
                    this.cryptoProcessor.getCertIssuerDN(), certificate.getSerialNumber().toString(),
                    this.cryptoProcessor.convertPublicKeyByteArray(spKeyPair.getPublic()));
            this.managerDAO.insertPKIData(descID, expiryDate.getTime(), keyStoreBytes, keyStorePassphrase,
                    keyPairName, keyPairPassphrase);
        }

    } catch (NumberFormatException e) {
        throw new ServiceCryptoCreationException(e.getLocalizedMessage(), e);
    } catch (ManagerDAOException e) {
        throw new ServiceCryptoCreationException(e.getLocalizedMessage(), e);
    } catch (CryptoException e) {
        throw new ServiceCryptoCreationException(e.getLocalizedMessage(), e);
    } catch (KeyStoreException e) {
        throw new ServiceCryptoCreationException("Could not obtain certificate from new keystore.", e);
    }
}

From source file:org.apache.ws.security.components.crypto.Merlin.java

/**
 * Get an X509 Certificate (chain) of the X500Principal argument in the supplied KeyStore 
 * @param subjectRDN either an X500Principal or a BouncyCastle X509Name instance.
 * @param store The KeyStore// ww w  . j av  a2s .  c  o m
 * @return an X509 Certificate (chain)
 * @throws WSSecurityException
 */
private Certificate[] getCertificates(byte[] thumbprint, KeyStore store, MessageDigest sha)
        throws WSSecurityException {
    try {
        for (Enumeration<String> e = store.aliases(); e.hasMoreElements();) {
            String alias = e.nextElement();
            Certificate cert = null;
            Certificate[] certs = store.getCertificateChain(alias);
            if (certs == null || certs.length == 0) {
                // no cert chain, so lets check if getCertificate gives us a result.
                cert = store.getCertificate(alias);
                if (cert == null) {
                    continue;
                }
                certs = new Certificate[] { cert };
            } else {
                cert = certs[0];
            }
            if (cert instanceof X509Certificate) {
                X509Certificate x509cert = (X509Certificate) cert;
                try {
                    sha.update(x509cert.getEncoded());
                } catch (CertificateEncodingException ex) {
                    throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE, "encodeError",
                            null, ex);
                }
                byte[] data = sha.digest();

                if (Arrays.equals(data, thumbprint)) {
                    return certs;
                }
            }
        }
    } catch (KeyStoreException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "keystore", null, e);
    }
    return new Certificate[] {};
}

From source file:org.wildfly.security.x500.cert.acme.AcmeClientSpiTest.java

@BeforeClass
public static void setUp() throws Exception {
    mockRetryAfter(); // no need to sleep in between polling attempts during testing
    KeyStore keyStore = KeyStore.getInstance("jks");
    try (InputStream is = AcmeClientSpiTest.class.getResourceAsStream(KEYSTORE)) {
        keyStore.load(is, KEYSTORE_PASSWORD);
    }/*from  ww w.  ja  v  a 2 s.  c  om*/

    int numAliases = keyStore.size();
    aliasToCertificateMap = new HashMap<>(numAliases);
    aliasToPrivateKeyMap = new HashMap<>(numAliases);
    final Enumeration<String> aliases = keyStore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        aliasToCertificateMap.put(alias, (X509Certificate) keyStore.getCertificate(alias));
        aliasToPrivateKeyMap.put(alias, (PrivateKey) keyStore.getKey(alias, KEYSTORE_PASSWORD));
    }
    server = new ClientAndServer(4001);
    client = new MockWebServer();
    client.start(5002); // this is the port our mock Let's Encrypt server will use to access the client
}

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

private SSLContext createSSLContext() {
    try {//from   w w  w. j av  a 2 s  .c  o m
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;

        if (this.keyStoreUrl != null) {
            KeyStore keystore = createStore(this.keyStoreUrl, this.keyStorePassword, this.keyStoreType);

            if (log.isDebugEnabled()) {
                for (Enumeration<String> aliases = keystore.aliases(); aliases.hasMoreElements();) {
                    String alias = aliases.nextElement();
                    Certificate[] certs = keystore.getCertificateChain(alias);
                    if (certs != null) {
                        log.debug("Certificate chain '{}':", alias);
                        for (int i = 0; i < certs.length; ++i) {
                            if (certs[i] instanceof X509Certificate) {
                                log.debug(" Certificate {}:", i + 1);
                                logCertificate((X509Certificate) certs[i]);
                            }
                        }
                    }
                }
            }

            keymanagers = createKeyManagers(keystore, this.keyStorePassword);
        }

        if (this.trustStoreUrl != null) {
            KeyStore keystore = createStore(this.trustStoreUrl, this.trustStorePassword, this.trustStoreType);

            if (log.isDebugEnabled()) {
                for (Enumeration<String> aliases = keystore.aliases(); aliases.hasMoreElements();) {
                    String alias = aliases.nextElement();
                    log.debug("Trusted certificate '{}':", alias);
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert instanceof X509Certificate) {
                        logCertificate((X509Certificate) trustedcert);
                    }
                }
            }

            trustmanagers = createTrustManagers(keystore);
        }

        SSLContext context = SSLContext.getInstance("SSL");
        context.init(keymanagers, trustmanagers, null);

        return context;
    } catch (NoSuchAlgorithmException e) {
        throw new LtSSLInitializationException("Unsupported algorithm exception: " + e.getMessage(), e);
    } catch (KeyStoreException e) {
        throw new LtSSLInitializationException("Keystore exception: " + e.getMessage(), e);
    } catch (GeneralSecurityException e) {
        throw new LtSSLInitializationException("Key management exception: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new LtSSLInitializationException(
                "I/O error reading key store/trust store file: " + e.getMessage(), e);
    }
}

From source file:com.mgmtp.jfunk.web.ssl.JFunkSSLSocketFactory.java

private SSLContext createSSLContext() {
    try {/*from  ww  w  .j  a  v  a  2s .c  om*/
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;

        if (this.keyStoreUrl != null) {
            KeyStore keystore = createStore(this.keyStoreUrl, this.keyStorePassword, this.keyStoreType);

            if (log.isDebugEnabled()) {
                for (Enumeration<String> aliases = keystore.aliases(); aliases.hasMoreElements();) {
                    String alias = aliases.nextElement();
                    Certificate[] certs = keystore.getCertificateChain(alias);
                    if (certs != null) {
                        log.debug("Certificate chain '{}':", alias);
                        for (int i = 0; i < certs.length; ++i) {
                            if (certs[i] instanceof X509Certificate) {
                                log.debug(" Certificate {}:", i + 1);
                                logCertificate((X509Certificate) certs[i]);
                            }
                        }
                    }
                }
            }

            keymanagers = createKeyManagers(keystore, this.keyStorePassword);
        }

        if (this.trustStoreUrl != null) {
            KeyStore keystore = createStore(this.trustStoreUrl, this.trustStorePassword, this.trustStoreType);

            if (log.isDebugEnabled()) {
                for (Enumeration<String> aliases = keystore.aliases(); aliases.hasMoreElements();) {
                    String alias = aliases.nextElement();
                    log.debug("Trusted certificate '{}':", alias);
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert instanceof X509Certificate) {
                        logCertificate((X509Certificate) trustedcert);
                    }
                }
            }

            trustmanagers = createTrustManagers(keystore);
        }

        SSLContext context = SSLContext.getInstance("SSL");
        context.init(keymanagers, trustmanagers, null);

        return context;
    } catch (NoSuchAlgorithmException e) {
        throw new JFunkException("Unsupported algorithm exception: " + e.getMessage(), e);
    } catch (KeyStoreException e) {
        throw new JFunkException("Keystore exception: " + e.getMessage(), e);
    } catch (GeneralSecurityException e) {
        throw new JFunkException("Key management exception: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new JFunkException("I/O error reading key store/trust store file: " + e.getMessage(), e);
    }
}