Example usage for java.security.cert X509Certificate equals

List of usage examples for java.security.cert X509Certificate equals

Introduction

In this page you can find the example usage for java.security.cert X509Certificate equals.

Prototype

public boolean equals(Object other) 

Source Link

Document

Compares this certificate for equality with the specified object.

Usage

From source file:gov.niem.ws.util.SecurityUtil.java

/**
 * Check that the certificate in the holder of key assertion matches
 * the passed certificate, sent via another channel (e.g. SSL client auth).
 * The certificate must be validated separately, before making this call.
 * @param assertion SAML holder of key assertion.
 * @param presentedCert certificate claimed to be presented in the HoK.
 * @return//from  w  w  w.  ja va  2  s  .  co  m
 * @throws IOException 
 * @throws SAXException 
 * @throws ParserConfigurationException 
 */
public static boolean confirmHolderOfKey(Document assertion, X509Certificate presentedCert)
        throws ParserConfigurationException, SAXException, IOException {
    Node keyInfoNode = null;
    try {
        keyInfoNode = (Node) subjectConfirmationKeyInfoPath.evaluate(assertion, XPathConstants.NODE);
    } catch (XPathExpressionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    }
    if (keyInfoNode == null) {
        System.out.println("key info not found in subject confirmation");
        return false;
    }
    X509Certificate assertionCert = getCertificateFromKeyInfo(keyInfoNode);
    if (assertionCert != null) {
        return assertionCert.equals(presentedCert);
    }

    PublicKey publicKey = getPublicKeyFromKeyInfo(keyInfoNode);
    if (publicKey != null) {
        return publicKey.equals(presentedCert.getPublicKey());
    }

    return false;
}

From source file:org.wso2.carbon.identity.authenticator.x509Certificate.X509CertificateUtil.java

private static boolean isUserCertificateValid(String userName, X509Certificate x509Certificate)
        throws AuthenticationFailedException {

    X509Certificate certInUserClaim = getCertificate(userName);
    if (log.isDebugEnabled()) {
        log.debug("X509 certificate with serial num: " + x509Certificate.getSerialNumber()
                + " is getting matched with the user certificate with serial num : "
                + certInUserClaim.getSerialNumber() + " in the user claim of user: " + userName);
    }/*from w  w  w .  jav a  2  s.c  om*/
    return x509Certificate.equals(certInUserClaim);
}

From source file:org.kse.crypto.x509.X509CertUtil.java

/**
 * Check whether or not a trusted certificate in the supplied KeyStore
 * matches the supplied X.509 certificate.
 *
 * @param cert//from   w  w  w  .  j av a2  s  . com
 *            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<String> aliases = keyStore.aliases(); aliases.hasMoreElements();) {
            String alias = 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: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 w  w  w  .  java 2  s  . c  om*/
 *            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:com.alfaariss.oa.profile.aselect.ws.security.OACrypto.java

/**
 * @see Crypto#getAliasForX509Cert(java.security.cert.Certificate)
 *///from w ww  .  ja  va  2  s  .c  o m
public String getAliasForX509Cert(Certificate cert) throws WSSecurityException {
    try {
        String alias = _factory.getCertificateAlias(cert);
        if (alias == null) {
            // Search
            Enumeration<String> aliases = _factory.getAliases();
            while (alias == null & aliases.hasMoreElements()) {
                String tAlias = aliases.nextElement();
                X509Certificate tempCert = (X509Certificate) _factory.getCertificate(alias);
                if (tempCert.equals(cert)) {
                    alias = tAlias;
                }
            }
        }
        return alias;
    } catch (CryptoException e) {
        _logger.error("Could not retrieve alias for X509 certificate", e);
        throw new WSSecurityException(WSSecurityException.FAILURE);
    }
}

From source file:org.atricore.idbus.capabilities.clientcertauthn.X509CertificateAuthScheme.java

/**
 * This method validates the input x509 certificate agaist the expected x509 certificate.
 *
 * @param inputX509Certificate    the X.509 Certificate supplied on authentication.
 * @param expectedX509Certificate the actual X.509 Certificate
 * @return true if the certificates match or false otherwise.
 *///  www.  j  av  a2s . c o  m
protected boolean validateX509Certificate(X509Certificate inputX509Certificate,
        X509Certificate expectedX509Certificate) {

    if (inputX509Certificate == null && expectedX509Certificate == null)
        return false;

    return inputX509Certificate.equals(expectedX509Certificate);
}

From source file:org.wso2.carbon.security.util.ServerCrypto.java

private String findAliasForCert(KeyStore ks, Certificate cert) throws KeyStoreException {
    Enumeration e = ks.aliases();
    while (e.hasMoreElements()) {
        String alias = (String) e.nextElement();
        X509Certificate cert2 = (X509Certificate) ks.getCertificate(alias);
        if (cert2.equals(cert)) {
            return alias;
        }//  w w w  .  ja v a 2  s  . c  o m
    }
    return null;
}

From source file:ee.ria.xroad.common.request.ManagementRequestClient.java

private void createCentralHttpClient() throws Exception {
    log.trace("createCentralHttpClient()");

    TrustManager tm = new X509TrustManager() {
        @Override/*from  w w  w. j av  a2  s. co m*/
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            if (chain.length == 0) {
                throw new CertificateException("Central server did not send TLS certificate");
            }

            X509Certificate centralServerSslCert = null;

            try {
                centralServerSslCert = GlobalConf.getCentralServerSslCertificate();
            } catch (Exception e) {
                throw new CertificateException("Could not get central server TLS certificate from global conf",
                        e);
            }

            if (centralServerSslCert == null) {
                throw new CertificateException("Central server TLS certificate is not in global conf");
            }

            if (!centralServerSslCert.equals(chain[0])) {
                throw new CertificateException("Central server TLS certificate does not match in global conf");
            }
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };

    centralHttpClient = createHttpClient(null, tm);
}

From source file:org.jscep.client.Client.java

private void verifyRA(final X509Certificate ca, final X509Certificate ra) throws ClientException {
    LOGGER.debug("Verifying signature of RA certificate");
    if (ca.equals(ra)) {
        LOGGER.debug("RA and CA are identical");

        return;// ww w .  j a  v a2s . c  o  m
    }
    try {
        JcaX509CertificateHolder raHolder = new JcaX509CertificateHolder(ra);

        ContentVerifierProvider verifierProvider = new JcaContentVerifierProviderBuilder().build(ca);

        if (!raHolder.isSignatureValid(verifierProvider)) {
            LOGGER.debug("Signature verification failed for RA.");
            throw new ClientException("RA not issued by CA");
        } else {
            LOGGER.debug("Signature verification passed for RA.");
        }
    } catch (CertException e) {
        throw new ClientException(e);
    } catch (CertificateEncodingException e) {
        throw new ClientException(e);
    } catch (OperatorCreationException e) {
        throw new ClientException(e);
    }
}

From source file:mitm.application.djigzo.workflow.impl.KeyAndCertificateWorkflowImpl.java

private void getPFXTransacted(Collection<X509Certificate> certificates, char[] password, boolean includeRoot,
        OutputStream pfx) throws KeyStoreException {
    try {/*w  w  w  .  j a v  a 2 s .  c o m*/
        KeyStore keyStore = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12");

        keyStore.load(null);

        for (X509Certificate certificate : certificates) {
            if (certificate == null) {
                continue;
            }

            X509CertStoreEntry entry = keyAndCertStore.getByCertificate(certificate);

            if (entry != null && entry.getCertificate() != null) {
                KeyAndCertificate keyAndCertificate = keyAndCertStore.getKeyAndCertificate(entry);

                if (keyAndCertificate != null) {
                    if (!certificate.equals(keyAndCertificate.getCertificate())) {
                        throw new IllegalStateException("Certificate mismatch.");
                    }

                    X509Certificate[] chain = null;

                    /*
                     * Build a certificate chain so we add the chain (if valid)
                     */
                    try {
                        CertificatePathBuilder pathBuilder = pathBuilderFactory.createCertificatePathBuilder();

                        CertPathBuilderResult pathBuilderResult = pathBuilder.buildPath(certificate);

                        X509Certificate root = null;

                        if (includeRoot && pathBuilderResult instanceof PKIXCertPathBuilderResult) {
                            TrustAnchor trustAnchor = ((PKIXCertPathBuilderResult) pathBuilderResult)
                                    .getTrustAnchor();

                            if (trustAnchor != null) {
                                root = trustAnchor.getTrustedCert();
                            }
                        }

                        CertPath certPath = pathBuilderResult.getCertPath();

                        if (certPath != null && CollectionUtils.isNotEmpty(certPath.getCertificates())) {
                            List<X509Certificate> completePath = new LinkedList<X509Certificate>();

                            for (Certificate fromPath : certPath.getCertificates()) {
                                if (!(fromPath instanceof X509Certificate)) {
                                    /*
                                     * only X509Certificates are supported
                                     */
                                    continue;
                                }

                                completePath.add((X509Certificate) fromPath);
                            }

                            if (root != null && includeRoot) {
                                completePath.add(root);
                            }

                            chain = new X509Certificate[completePath.size()];

                            chain = completePath.toArray(chain);
                        }
                    } catch (CertPathBuilderException e) {
                        logger.warn(
                                "Could not build a path. Message: " + ExceptionUtils.getRootCauseMessage(e));
                    }

                    if (ArrayUtils.getLength(chain) == 0) {
                        chain = new X509Certificate[] { certificate };
                    }

                    String alias = X509CertificateInspector.getThumbprint(certificate);

                    if (keyAndCertificate.getPrivateKey() != null) {
                        keyStore.setKeyEntry(alias, keyAndCertificate.getPrivateKey(), password, chain);
                    } else {
                        keyStore.setCertificateEntry(alias, certificate);
                    }
                }
            }
        }

        keyStore.store(pfx, password);
    } catch (NoSuchAlgorithmException e) {
        throw new KeyStoreException(e);
    } catch (CertificateException e) {
        throw new KeyStoreException(e);
    } catch (IOException e) {
        throw new KeyStoreException(e);
    } catch (CertStoreException e) {
        throw new KeyStoreException(e);
    } catch (NoSuchProviderException e) {
        throw new NoSuchProviderRuntimeException(e);
    } catch (SecurityFactoryFactoryException e) {
        throw new KeyStoreException(e);
    }
}