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:nu.yona.server.AppServiceApplication.java

@Bean
@Qualifier("appleMobileConfigSigningCertificate")
public X509Certificate appleMobileConfigSigningCertificate(KeyStore keyStore) {
    try {//w  w w .j a  v  a 2  s . com
        return (X509Certificate) keyStore
                .getCertificate(yonaProperties.getAppleMobileConfig().getSigningAlias());
    } catch (KeyStoreException e) {
        throw YonaException.unexpected(e);
    }
}

From source file:net.link.util.common.KeyUtils.java

public static ImmutableMap<String, X509Certificate> getCertificates(KeyStore keyStore,
        Predicate<String> ignoreAlias) {

    Enumeration<String> aliases;
    try {/*from w  w w . j  av  a  2  s.  c  o m*/
        aliases = keyStore.aliases();
    } catch (KeyStoreException e) {
        throw new InternalInconsistencyException("could not enumerate aliases", e);
    }

    ImmutableMap.Builder<String, X509Certificate> certificates = ImmutableMap.builder();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (ignoreAlias != null && ignoreAlias.apply(alias))
            continue;

        try {
            if (keyStore.isCertificateEntry(alias))
                certificates.put(alias, (X509Certificate) keyStore.getCertificate(alias));
        } catch (KeyStoreException e) {
            throw new InternalInconsistencyException(
                    String.format("error retrieving certificate, alias=%s", alias), e);
        }
    }

    return certificates.build();
}

From source file:net.sf.keystore_explorer.crypto.x509.X509CertUtil.java

/**
 * Check whether or not a trusted certificate in the supplied KeyStore
 * matches the supplied X.509 certificate.
 *
 * @param cert//from www .  java  2s  .c  o  m
 *            The certificate
 * @param keyStore
 *            The KeyStore
 * @return The alias of the matching certificate in the KeyStore or null if
 *         there is no match
 * @throws CryptoException
 *             If there is a problem establishing trust
 */
public static String matchCertificate(KeyStore keyStore, X509Certificate cert) throws CryptoException {
    try {
        for (Enumeration aliases = keyStore.aliases(); aliases.hasMoreElements();) {
            String alias = (String) aliases.nextElement();
            if (keyStore.isCertificateEntry(alias)) {
                X509Certificate compCert = X509CertUtil.convertCertificate(keyStore.getCertificate(alias));

                if (cert.equals(compCert)) {
                    return alias;
                }
            }
        }
        return null;
    } catch (KeyStoreException ex) {
        throw new CryptoException(res.getString("NoMatchCertificate.exception.message"), ex);
    }
}

From source file:org.jaggeryjs.modules.sso.common.util.Util.java

private static boolean validateSignature(Signature signature, String keyStoreName, String keyStorePassword,
        String alias, int tenantId, String tenantDomain) {
    boolean isSigValid = false;
    try {/*  w ww.  j a  v  a2s .  c o  m*/
        KeyStore keyStore = null;
        java.security.cert.X509Certificate cert = null;
        if (tenantId != MultitenantConstants.SUPER_TENANT_ID) {
            // get an instance of the corresponding Key Store Manager instance
            KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(tenantId);
            keyStore = keyStoreManager.getKeyStore(generateKSNameFromDomainName(tenantDomain));
            cert = (java.security.cert.X509Certificate) keyStore.getCertificate(tenantDomain);
        } else {
            keyStore = KeyStore.getInstance("JKS");
            keyStore.load(new FileInputStream(new File(keyStoreName)), keyStorePassword.toCharArray());
            cert = (java.security.cert.X509Certificate) keyStore.getCertificate(alias);
        }
        try {
            SAMLSignatureProfileValidator signatureProfileValidator = new SAMLSignatureProfileValidator();
            signatureProfileValidator.validate(signature);

            // Following code segment is taken from org.opensaml.security.SAMLSignatureProfileValidator
            // of OpenSAML 2.6.4. This is done to get the latest XSW related fixes.

            SignatureImpl sigImpl = (SignatureImpl) signature;
            XMLSignature apacheSig = sigImpl.getXMLSignature();
            SignableSAMLObject signableObject = (SignableSAMLObject) sigImpl.getParent();

            Reference ref = null;
            try {
                ref = apacheSig.getSignedInfo().item(0);
            } catch (XMLSecurityException e) {
                // This exception should never occur, because it's already checked
                // from the previous call to signatureProfileValidator#validate
                log.error("Apache XML Security exception obtaining Reference", e);
                throw new ValidationException("Could not obtain Reference from Signature/SignedInfo", e);
            }

            String uri = ref.getURI();

            validateReferenceURI(uri, signableObject);
            validateObjectChildren(apacheSig);

            // End of OpenSAML 2.6.4 logic
        } catch (ValidationException e) {
            String logMsg = "Signature do not confirm to SAML signature profile. Possible XML Signature Wrapping "
                    + "Attack!";
            log.warn(logMsg);
            if (log.isDebugEnabled()) {
                log.debug(logMsg, e);
            }
            return isSigValid;
        }

        X509CredentialImpl credentialImpl = new X509CredentialImpl(cert);
        SignatureValidator signatureValidator = new SignatureValidator(credentialImpl);
        signatureValidator.validate(signature);
        isSigValid = true;
        return isSigValid;
    } catch (Exception e) {
        log.error("Error while validating signature", e);
        return isSigValid;
    }
}

From source file:com.netflix.niws.client.http.SecureRestClientKeystoreTest.java

@Test
public void testGetKeystoreWithNoClientAuth() throws Exception {

    // jks format
    byte[] dummyTruststore = Base64.decode(SecureGetTest.TEST_TS1);
    byte[] dummyKeystore = Base64.decode(SecureGetTest.TEST_KS1);

    File tempKeystore = File.createTempFile(this.getClass().getName(), ".keystore");
    File tempTruststore = File.createTempFile(this.getClass().getName(), ".truststore");

    FileOutputStream keystoreFileOut = new FileOutputStream(tempKeystore);
    try {/*ww w .  ja  v a  2  s .c o  m*/
        keystoreFileOut.write(dummyKeystore);
    } finally {
        keystoreFileOut.close();
    }

    FileOutputStream truststoreFileOut = new FileOutputStream(tempTruststore);
    try {
        truststoreFileOut.write(dummyTruststore);
    } finally {
        truststoreFileOut.close();
    }

    AbstractConfiguration cm = ConfigurationManager.getConfigInstance();

    String name = this.getClass().getName() + ".test2";

    String configPrefix = name + "." + "ribbon";

    cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsSecure, "true");
    cm.setProperty(configPrefix + "." + CommonClientConfigKey.KeyStore, tempKeystore.getAbsolutePath());
    cm.setProperty(configPrefix + "." + CommonClientConfigKey.KeyStorePassword, "changeit");

    RestClient client = (RestClient) ClientFactory.getNamedClient(name);

    KeyStore keyStore = client.getKeyStore();

    Certificate cert = keyStore.getCertificate("ribbon_key");

    assertNotNull(cert);
}

From source file:com.netflix.niws.client.http.SecureRestClientKeystoreTest.java

@Test
public void testGetKeystoreWithClientAuth() throws Exception {

    // jks format
    byte[] dummyTruststore = Base64.decode(SecureGetTest.TEST_TS1);
    byte[] dummyKeystore = Base64.decode(SecureGetTest.TEST_KS1);

    File tempKeystore = File.createTempFile(this.getClass().getName(), ".keystore");
    File tempTruststore = File.createTempFile(this.getClass().getName(), ".truststore");

    FileOutputStream keystoreFileOut = new FileOutputStream(tempKeystore);
    try {//w  ww . j  a va2 s .  c  o m
        keystoreFileOut.write(dummyKeystore);
    } finally {
        keystoreFileOut.close();
    }

    FileOutputStream truststoreFileOut = new FileOutputStream(tempTruststore);
    try {
        truststoreFileOut.write(dummyTruststore);
    } finally {
        truststoreFileOut.close();
    }

    AbstractConfiguration cm = ConfigurationManager.getConfigInstance();

    String name = this.getClass().getName() + ".test1";

    String configPrefix = name + "." + "ribbon";

    cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsSecure, "true");
    cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsClientAuthRequired, "true");
    cm.setProperty(configPrefix + "." + CommonClientConfigKey.KeyStore, tempKeystore.getAbsolutePath());
    cm.setProperty(configPrefix + "." + CommonClientConfigKey.KeyStorePassword, "changeit");
    cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStore, tempTruststore.getAbsolutePath());
    cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStorePassword, "changeit");

    RestClient client = (RestClient) ClientFactory.getNamedClient(name);

    KeyStore keyStore = client.getKeyStore();

    Certificate cert = keyStore.getCertificate("ribbon_key");

    assertNotNull(cert);

}

From source file:com.netscape.cmstools.pkcs11.PKCS11CertRemoveCLI.java

public void execute(String[] args) throws Exception {

    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("help")) {
        printHelp();/*w  w w.j a v  a 2 s . c  o m*/
        return;
    }

    if (cmd.hasOption("verbose")) {
        PKILogger.setLevel(PKILogger.Level.INFO);

    } else if (cmd.hasOption("debug")) {
        PKILogger.setLevel(PKILogger.Level.DEBUG);
    }

    String[] cmdArgs = cmd.getArgs();

    if (cmdArgs.length < 1) {
        throw new Exception("Missing cert ID.");
    }

    String alias = cmdArgs[0];

    String tokenName = getConfig().getTokenName();
    CryptoToken token = CryptoUtil.getKeyStorageToken(tokenName);

    KeyStore ks = KeyStore.getInstance("pkcs11");
    ks.load(new JSSLoadStoreParameter(token));

    Certificate cert = ks.getCertificate(alias);

    if (cert == null) {
        throw new Exception("Certificate not found: " + alias);
    }

    ks.deleteEntry(alias);
}

From source file:com.netscape.cmstools.pkcs11.PKCS11CertShowCLI.java

public void execute(String[] args) throws Exception {

    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("help")) {
        printHelp();// w  ww .  j  ava  2 s. c o m
        return;
    }

    if (cmd.hasOption("verbose")) {
        PKILogger.setLevel(PKILogger.Level.INFO);

    } else if (cmd.hasOption("debug")) {
        PKILogger.setLevel(PKILogger.Level.DEBUG);
    }

    String[] cmdArgs = cmd.getArgs();

    if (cmdArgs.length < 1) {
        throw new Exception("Missing cert ID.");
    }

    String alias = cmdArgs[0];

    String tokenName = getConfig().getTokenName();
    CryptoToken token = CryptoUtil.getKeyStorageToken(tokenName);

    KeyStore ks = KeyStore.getInstance("pkcs11");
    ks.load(new JSSLoadStoreParameter(token));

    Certificate cert = ks.getCertificate(alias);

    if (cert == null) {
        throw new Exception("Certificate not found: " + alias);
    }

    PKCS11CertCLI.printCertInfo(alias, cert);
}

From source file:net.sf.keystore_explorer.crypto.x509.X509CertUtil.java

private static List<X509Certificate> extractCertificates(KeyStore keyStore) throws CryptoException {
    try {/*from w  w  w. ja v  a  2s  . c om*/
        List<X509Certificate> certs = new ArrayList<X509Certificate>();

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

            if (keyStore.isCertificateEntry(alias)) {
                certs.add(X509CertUtil.convertCertificate(keyStore.getCertificate(alias)));
            }
        }

        return certs;
    } catch (KeyStoreException ex) {
        throw new CryptoException(res.getString("NoExtractCertificates.exception.message"), ex);
    }
}

From source file:net.sf.keystore_explorer.gui.actions.ExportTrustedCertificatePublicKeyAction.java

private PublicKey getPublicKey(String alias) throws CryptoException {
    try {/*from  w w  w  .  j a  va 2 s. c o  m*/
        KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory();
        KeyStore keyStore = history.getCurrentState().getKeyStore();

        X509Certificate cert = X509CertUtil.convertCertificate(keyStore.getCertificate(alias));

        return cert.getPublicKey();
    } catch (KeyStoreException ex) {
        String message = MessageFormat
                .format(res.getString("ExportTrustedCertificatePublicKeyAction.NoAccessEntry.message"), alias);
        throw new CryptoException(message, ex);
    }
}