Java Code Examples for java.security.cert.X509Certificate#equals()

The following examples show how to use java.security.cert.X509Certificate#equals() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ForwardBuilder.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Verifies whether the input certificate completes the path.
 * Checks the cert against each trust anchor that was specified, in order,
 * and returns true as soon as it finds a valid anchor.
 * Returns true if the cert matches a trust anchor specified as a
 * certificate or if the cert verifies with a trust anchor that
 * was specified as a trusted {pubkey, caname} pair. Returns false if none
 * of the trust anchors are valid for this cert.
 *
 * @param cert the certificate to test
 * @return a boolean value indicating whether the cert completes the path.
 */
@Override
boolean isPathCompleted(X509Certificate cert) {
    for (TrustAnchor anchor : trustAnchors) {
        if (anchor.getTrustedCert() != null) {
            if (cert.equals(anchor.getTrustedCert())) {
                this.trustAnchor = anchor;
                return true;
            } else {
                continue;
            }
        }
        X500Principal principal = anchor.getCA();
        PublicKey publicKey = anchor.getCAPublicKey();

        if (principal != null && publicKey != null &&
                principal.equals(cert.getSubjectX500Principal())) {
            if (publicKey.equals(cert.getPublicKey())) {
                // the cert itself is a trust anchor
                this.trustAnchor = anchor;
                return true;
            }
            // else, it is a self-issued certificate of the anchor
        }

        // Check subject/issuer name chaining
        if (principal == null ||
                !principal.equals(cert.getIssuerX500Principal())) {
            continue;
        }

        // skip anchor if it contains a DSA key with no DSA params
        if (PKIX.isDSAPublicKeyWithoutParams(publicKey)) {
            continue;
        }

        /*
         * Check signature
         */
        try {
            cert.verify(publicKey, buildParams.sigProvider());
        } catch (InvalidKeyException ike) {
            if (debug != null) {
                debug.println("ForwardBuilder.isPathCompleted() invalid "
                              + "DSA key found");
            }
            continue;
        } catch (GeneralSecurityException e){
            if (debug != null) {
                debug.println("ForwardBuilder.isPathCompleted() " +
                              "unexpected exception");
                e.printStackTrace();
            }
            continue;
        }

        this.trustAnchor = anchor;
        return true;
    }

    return false;
}
 
Example 2
Source File: MultiTrustManager.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
protected boolean isTrusted(X509Certificate[] cert) {
    if (cert != null) {
        X509Certificate[] issuers = this.getAcceptedIssuers();
        for (X509Certificate issuer: issuers) {
            for (X509Certificate c: cert) {
                if (Debug.verboseOn()) {
                    Debug.logVerbose("--- Checking cert: " + issuer.getSubjectX500Principal() + " vs " + c.getSubjectX500Principal(), module);
                }
                if (issuer.equals(c)) {
                    if (Debug.verboseOn()) {
                        Debug.logVerbose("--- Found trusted cert: " + issuer.getSerialNumber().toString(16) + " : " + issuer.getSubjectX500Principal(), module);
                    }
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 3
Source File: RFC3281CertPathUtilities.java    From ripple-lib-java with ISC License 6 votes vote down vote up
protected static void processAttrCert4(X509Certificate acIssuerCert,
    Set trustedACIssuers) throws CertPathValidatorException
{
    Set set = trustedACIssuers;
    boolean trusted = false;
    for (Iterator it = set.iterator(); it.hasNext();)
    {
        TrustAnchor anchor = (TrustAnchor) it.next();
        if (acIssuerCert.getSubjectX500Principal().getName("RFC2253")
            .equals(anchor.getCAName())
            || acIssuerCert.equals(anchor.getTrustedCert()))
        {
            trusted = true;
        }
    }
    if (!trusted)
    {
        throw new CertPathValidatorException(
            "Attribute certificate issuer is not directly trusted.");
    }
}
 
Example 4
Source File: RFC3281CertPathUtilities.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
protected static void processAttrCert4(X509Certificate acIssuerCert,
    Set trustedACIssuers) throws CertPathValidatorException
{
    Set set = trustedACIssuers;
    boolean trusted = false;
    for (Iterator it = set.iterator(); it.hasNext();)
    {
        TrustAnchor anchor = (TrustAnchor) it.next();
        if (acIssuerCert.getSubjectX500Principal().getName("RFC2253")
            .equals(anchor.getCAName())
            || acIssuerCert.equals(anchor.getTrustedCert()))
        {
            trusted = true;
        }
    }
    if (!trusted)
    {
        throw new CertPathValidatorException(
            "Attribute certificate issuer is not directly trusted.");
    }
}
 
Example 5
Source File: AbstractSupportingTokenPolicyValidator.java    From steady with Apache License 2.0 5 votes vote down vote up
/**
 * Get a security result representing an EncryptedKey that matches the parameter.
 */
private WSSecurityEngineResult getMatchingEncryptedKey(X509Certificate cert) {
    for (WSSecurityEngineResult wser : results) {
        Integer actInt = (Integer)wser.get(WSSecurityEngineResult.TAG_ACTION);
        if (actInt.intValue() == WSConstants.ENCR) {
            X509Certificate encrCert = 
                (X509Certificate)wser.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
            if (cert.equals(encrCert)) {
                return wser;
            }
        }
    }
    return null;
}
 
Example 6
Source File: DViewCertificate.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
@Override
public int compare(X509Certificate cert1, X509Certificate cert2) {

	// Compare certificates for equality. Where all we care about is if
	// the certificates are equal or not - the order is unimportant
	if (cert1.equals(cert2)) {
		return 0;
	}

	// Compare on subject DN
	int i = cert1.getSubjectX500Principal().toString().compareTo(cert2.getSubjectX500Principal().toString());

	if (i != 0) {
		return i;
	}

	// Compare on issuer DN
	i = cert1.getIssuerX500Principal().toString().compareTo(cert2.getIssuerX500Principal().toString());

	if (i != 0) {
		return i;
	}

	// If all else fails then compare serial numbers - if this is the
	// same and the DNs are the same then it is probably the same
	// certificate anyway
	return cert1.getSerialNumber().subtract(cert2.getSerialNumber()).intValue();
}
 
Example 7
Source File: AbstractSupportingTokenPolicyValidator.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Get a security result representing an EncryptedKey that matches the parameter.
 */
private WSSecurityEngineResult getMatchingEncryptedKey(X509Certificate cert,
                                                       WSHandlerResult results) {
    if (results.getActionResults().containsKey(WSConstants.ENCR)) {
        for (WSSecurityEngineResult wser : results.getActionResults().get(WSConstants.ENCR)) {
            X509Certificate encrCert =
                (X509Certificate)wser.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
            if (cert.equals(encrCert)) {
                return wser;
            }
        }
    }
    return null;
}
 
Example 8
Source File: ServerCrypto.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
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;
        }
    }
    return null;
}
 
Example 9
Source File: MemorizingTrustManager.java    From Pix-Art-Messenger with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean verify(String domain, String hostname, SSLSession session) {
    LOGGER.log(Level.FINE, "hostname verifier for " + domain + ", trying default verifier first");
    // if the default verifier accepts the hostname, we are done
    if (defaultVerifier instanceof DomainHostnameVerifier) {
        if (((DomainHostnameVerifier) defaultVerifier).verify(domain, hostname, session)) {
            return true;
        }
    } else {
        if (defaultVerifier.verify(domain, session)) {
            return true;
        }
    }


    // otherwise, we check if the hostname is an alias for this cert in our keystore
    try {
        X509Certificate cert = (X509Certificate) session.getPeerCertificates()[0];
        //Log.d(TAG, "cert: " + cert);
        if (cert.equals(appKeyStore.getCertificate(domain.toLowerCase(Locale.US)))) {
            LOGGER.log(Level.FINE, "certificate for " + domain + " is in our keystore. accepting.");
            return true;
        } else {
            LOGGER.log(Level.FINE, "server " + domain + " provided wrong certificate, asking user.");
            if (interactive) {
                return interactHostname(cert, domain);
            } else {
                return false;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}
 
Example 10
Source File: AbstractSupportingTokenPolicyValidator.java    From steady with Apache License 2.0 5 votes vote down vote up
/**
 * Get a security result representing an EncryptedKey that matches the parameter.
 */
private WSSecurityEngineResult getMatchingEncryptedKey(X509Certificate cert) {
    for (WSSecurityEngineResult wser : results) {
        Integer actInt = (Integer)wser.get(WSSecurityEngineResult.TAG_ACTION);
        if (actInt.intValue() == WSConstants.ENCR) {
            X509Certificate encrCert = 
                (X509Certificate)wser.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
            if (cert.equals(encrCert)) {
                return wser;
            }
        }
    }
    return null;
}
 
Example 11
Source File: AbstractSupportingTokenPolicyValidator.java    From steady with Apache License 2.0 5 votes vote down vote up
/**
 * Get a security result representing an EncryptedKey that matches the parameter.
 */
private WSSecurityEngineResult getMatchingEncryptedKey(X509Certificate cert) {
    for (WSSecurityEngineResult wser : results) {
        Integer actInt = (Integer)wser.get(WSSecurityEngineResult.TAG_ACTION);
        if (actInt.intValue() == WSConstants.ENCR) {
            X509Certificate encrCert = 
                (X509Certificate)wser.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
            if (cert.equals(encrCert)) {
                return wser;
            }
        }
    }
    return null;
}
 
Example 12
Source File: MemorizingTrustManager.java    From Conversations with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean verify(String domain, String hostname, SSLSession session) {
    LOGGER.log(Level.FINE, "hostname verifier for " + domain + ", trying default verifier first");
    // if the default verifier accepts the hostname, we are done
    if (defaultVerifier instanceof DomainHostnameVerifier) {
        if (((DomainHostnameVerifier) defaultVerifier).verify(domain, hostname, session)) {
            return true;
        }
    } else {
        if (defaultVerifier.verify(domain, session)) {
            return true;
        }
    }


    // otherwise, we check if the hostname is an alias for this cert in our keystore
    try {
        X509Certificate cert = (X509Certificate) session.getPeerCertificates()[0];
        //Log.d(TAG, "cert: " + cert);
        if (cert.equals(appKeyStore.getCertificate(domain.toLowerCase(Locale.US)))) {
            LOGGER.log(Level.FINE, "certificate for " + domain + " is in our keystore. accepting.");
            return true;
        } else {
            LOGGER.log(Level.FINE, "server " + domain + " provided wrong certificate, asking user.");
            if (interactive) {
                return interactHostname(cert, domain);
            } else {
                return false;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}
 
Example 13
Source File: GenericX509TrustManager.java    From Android-Application-ZJB with Apache License 2.0 5 votes vote down vote up
private X509Certificate findRootCert(List<X509Certificate> certificates) {
    X509Certificate rootCert = null;
    Iterator iterator = certificates.iterator();

    while (iterator.hasNext()) {
        X509Certificate cert = (X509Certificate) iterator.next();
        X509Certificate signer = this.findSigner(cert, certificates);
        if (signer == null || signer.equals(cert)) {
            rootCert = cert;
            break;
        }
    }

    return rootCert;
}
 
Example 14
Source File: JarVerifier.java    From offspring with MIT License 5 votes vote down vote up
public static boolean isTrusted(X509Certificate cert,
    X509Certificate[] trustedCaCerts) {
  // Return true iff either of the following is true:
  // 1) the cert is in the trustedCaCerts.
  // 2) the cert is issued by a trusted CA.

  // Check whether the cert is in the trustedCaCerts
  for (int i = 0; i < trustedCaCerts.length; i++) {
    // If the cert has the same SubjectDN
    // as a trusted CA, check whether
    // the two certs are the same.
    if (cert.getSubjectDN().equals(trustedCaCerts[i].getSubjectDN())) {
      if (cert.equals(trustedCaCerts[i])) { return true; }
    }
  }

  // Check whether the cert is issued by a trusted CA.
  // Signature verification is expensive. So we check
  // whether the cert is issued
  // by one of the trusted CAs if the above loop failed.
  for (int i = 0; i < trustedCaCerts.length; i++) {
    // If the issuer of the cert has the same name as
    // a trusted CA, check whether that trusted CA
    // actually issued the cert.
    if (cert.getIssuerDN().equals(trustedCaCerts[i].getSubjectDN())) {
      try {
        cert.verify(trustedCaCerts[i].getPublicKey());
        return true;
      }
      catch (Exception e) {
        // Do nothing.
      }
    }
  }

  return false;
}
 
Example 15
Source File: ForwardBuilder.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Verifies whether the input certificate completes the path.
 * Checks the cert against each trust anchor that was specified, in order,
 * and returns true as soon as it finds a valid anchor.
 * Returns true if the cert matches a trust anchor specified as a
 * certificate or if the cert verifies with a trust anchor that
 * was specified as a trusted {pubkey, caname} pair. Returns false if none
 * of the trust anchors are valid for this cert.
 *
 * @param cert the certificate to test
 * @return a boolean value indicating whether the cert completes the path.
 */
@Override
boolean isPathCompleted(X509Certificate cert) {
    for (TrustAnchor anchor : trustAnchors) {
        if (anchor.getTrustedCert() != null) {
            if (cert.equals(anchor.getTrustedCert())) {
                this.trustAnchor = anchor;
                return true;
            } else {
                continue;
            }
        }
        X500Principal principal = anchor.getCA();
        PublicKey publicKey = anchor.getCAPublicKey();

        if (principal != null && publicKey != null &&
                principal.equals(cert.getSubjectX500Principal())) {
            if (publicKey.equals(cert.getPublicKey())) {
                // the cert itself is a trust anchor
                this.trustAnchor = anchor;
                return true;
            }
            // else, it is a self-issued certificate of the anchor
        }

        // Check subject/issuer name chaining
        if (principal == null ||
                !principal.equals(cert.getIssuerX500Principal())) {
            continue;
        }

        // skip anchor if it contains a DSA key with no DSA params
        if (PKIX.isDSAPublicKeyWithoutParams(publicKey)) {
            continue;
        }

        /*
         * Check signature
         */
        try {
            cert.verify(publicKey, buildParams.sigProvider());
        } catch (InvalidKeyException ike) {
            if (debug != null) {
                debug.println("ForwardBuilder.isPathCompleted() invalid "
                              + "DSA key found");
            }
            continue;
        } catch (GeneralSecurityException e){
            if (debug != null) {
                debug.println("ForwardBuilder.isPathCompleted() " +
                              "unexpected exception");
                e.printStackTrace();
            }
            continue;
        }

        this.trustAnchor = anchor;
        return true;
    }

    return false;
}
 
Example 16
Source File: AbstractSupportingTokenPolicyValidator.java    From steady with Apache License 2.0 4 votes vote down vote up
/**
 * Check that a WSSecurityEngineResult corresponding to a signature or encryption uses the same 
 * signing/encrypting credential as one of the tokens.
 * @param signatureResult a WSSecurityEngineResult corresponding to a signature or encryption
 * @param tokenResult A list of WSSecurityEngineResults corresponding to tokens
 * @return 
 */
private boolean checkSignatureOrEncryptionResult(
    WSSecurityEngineResult result,
    List<WSSecurityEngineResult> tokenResult
) {
    // See what was used to sign/encrypt this result
    X509Certificate cert = 
        (X509Certificate)result.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
    byte[] secret = (byte[])result.get(WSSecurityEngineResult.TAG_SECRET);
    PublicKey publicKey = 
        (PublicKey)result.get(WSSecurityEngineResult.TAG_PUBLIC_KEY);
    
    // Now see if the same credential exists in the tokenResult list
    for (WSSecurityEngineResult token : tokenResult) {
        Integer actInt = (Integer)token.get(WSSecurityEngineResult.TAG_ACTION);
        BinarySecurity binarySecurity = 
            (BinarySecurity)token.get(WSSecurityEngineResult.TAG_BINARY_SECURITY_TOKEN);
        if (binarySecurity instanceof X509Security
            || binarySecurity instanceof PKIPathSecurity) {
            X509Certificate foundCert = 
                (X509Certificate)token.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
            if (foundCert.equals(cert)) {
                return true;
            }
        } else if (actInt.intValue() == WSConstants.ST_SIGNED
            || actInt.intValue() == WSConstants.ST_UNSIGNED) {
            AssertionWrapper assertionWrapper = 
                (AssertionWrapper)token.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
            SAMLKeyInfo samlKeyInfo = assertionWrapper.getSubjectKeyInfo();
            if (samlKeyInfo != null) {
                X509Certificate[] subjectCerts = samlKeyInfo.getCerts();
                byte[] subjectSecretKey = samlKeyInfo.getSecret();
                PublicKey subjectPublicKey = samlKeyInfo.getPublicKey();
                if ((cert != null && subjectCerts != null && cert.equals(subjectCerts[0]))
                    || (subjectSecretKey != null && Arrays.equals(subjectSecretKey, secret))
                    || (subjectPublicKey != null && subjectPublicKey.equals(publicKey))) {
                    return true;
                }
            }
        } else if (publicKey != null) {
            PublicKey foundPublicKey = 
                (PublicKey)token.get(WSSecurityEngineResult.TAG_PUBLIC_KEY);
            if (publicKey.equals(foundPublicKey)) {
                return true;
            }
        } else {
            byte[] foundSecret = (byte[])token.get(WSSecurityEngineResult.TAG_SECRET);
            byte[] derivedKey = 
                (byte[])token.get(WSSecurityEngineResult.TAG_ENCRYPTED_EPHEMERAL_KEY);
            if ((foundSecret != null && Arrays.equals(foundSecret, secret))
                || (derivedKey != null && Arrays.equals(derivedKey, secret))) {
                return true;
            }
        }
    }
    
    return false;
}
 
Example 17
Source File: ForwardBuilder.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Verifies whether the input certificate completes the path.
 * Checks the cert against each trust anchor that was specified, in order,
 * and returns true as soon as it finds a valid anchor.
 * Returns true if the cert matches a trust anchor specified as a
 * certificate or if the cert verifies with a trust anchor that
 * was specified as a trusted {pubkey, caname} pair. Returns false if none
 * of the trust anchors are valid for this cert.
 *
 * @param cert the certificate to test
 * @return a boolean value indicating whether the cert completes the path.
 */
@Override
boolean isPathCompleted(X509Certificate cert) {
    for (TrustAnchor anchor : trustAnchors) {
        if (anchor.getTrustedCert() != null) {
            if (cert.equals(anchor.getTrustedCert())) {
                this.trustAnchor = anchor;
                return true;
            } else {
                continue;
            }
        }
        X500Principal principal = anchor.getCA();
        PublicKey publicKey = anchor.getCAPublicKey();

        if (principal != null && publicKey != null &&
                principal.equals(cert.getSubjectX500Principal())) {
            if (publicKey.equals(cert.getPublicKey())) {
                // the cert itself is a trust anchor
                this.trustAnchor = anchor;
                return true;
            }
            // else, it is a self-issued certificate of the anchor
        }

        // Check subject/issuer name chaining
        if (principal == null ||
                !principal.equals(cert.getIssuerX500Principal())) {
            continue;
        }

        // skip anchor if it contains a DSA key with no DSA params
        if (PKIX.isDSAPublicKeyWithoutParams(publicKey)) {
            continue;
        }

        /*
         * Check signature
         */
        try {
            if (buildParams.sigProvider() != null) {
                cert.verify(publicKey, buildParams.sigProvider());
            } else {
                cert.verify(publicKey);
            }
        } catch (InvalidKeyException ike) {
            if (debug != null) {
                debug.println("ForwardBuilder.isPathCompleted() invalid "
                              + "DSA key found");
            }
            continue;
        } catch (GeneralSecurityException e){
            if (debug != null) {
                debug.println("ForwardBuilder.isPathCompleted() " +
                              "unexpected exception");
                e.printStackTrace();
            }
            continue;
        }

        this.trustAnchor = anchor;
        return true;
    }

    return false;
}
 
Example 18
Source File: ForwardBuilder.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Verifies whether the input certificate completes the path.
 * Checks the cert against each trust anchor that was specified, in order,
 * and returns true as soon as it finds a valid anchor.
 * Returns true if the cert matches a trust anchor specified as a
 * certificate or if the cert verifies with a trust anchor that
 * was specified as a trusted {pubkey, caname} pair. Returns false if none
 * of the trust anchors are valid for this cert.
 *
 * @param cert the certificate to test
 * @return a boolean value indicating whether the cert completes the path.
 */
@Override
boolean isPathCompleted(X509Certificate cert) {
    for (TrustAnchor anchor : trustAnchors) {
        if (anchor.getTrustedCert() != null) {
            if (cert.equals(anchor.getTrustedCert())) {
                this.trustAnchor = anchor;
                return true;
            } else {
                continue;
            }
        }
        X500Principal principal = anchor.getCA();
        PublicKey publicKey = anchor.getCAPublicKey();

        if (principal != null && publicKey != null &&
                principal.equals(cert.getSubjectX500Principal())) {
            if (publicKey.equals(cert.getPublicKey())) {
                // the cert itself is a trust anchor
                this.trustAnchor = anchor;
                return true;
            }
            // else, it is a self-issued certificate of the anchor
        }

        // Check subject/issuer name chaining
        if (principal == null ||
                !principal.equals(cert.getIssuerX500Principal())) {
            continue;
        }

        // skip anchor if it contains a DSA key with no DSA params
        if (PKIX.isDSAPublicKeyWithoutParams(publicKey)) {
            continue;
        }

        /*
         * Check signature
         */
        try {
            cert.verify(publicKey, buildParams.sigProvider());
        } catch (InvalidKeyException ike) {
            if (debug != null) {
                debug.println("ForwardBuilder.isPathCompleted() invalid "
                              + "DSA key found");
            }
            continue;
        } catch (GeneralSecurityException e){
            if (debug != null) {
                debug.println("ForwardBuilder.isPathCompleted() " +
                              "unexpected exception");
                e.printStackTrace();
            }
            continue;
        }

        this.trustAnchor = anchor;
        return true;
    }

    return false;
}
 
Example 19
Source File: BasicCertificateChainCleaner.java    From styT with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a cleaned chain for {@code chain}.
 *
 * <p>This method throws if the complete chain to a trusted CA certificate cannot be constructed.
 * This is unexpected unless the trust root index in this class has a different trust manager than
 * what was used to establish {@code chain}.
 */
@Override public List<Certificate> clean(List<Certificate> chain, String hostname)
    throws SSLPeerUnverifiedException {
  Deque<Certificate> queue = new ArrayDeque<>(chain);
  List<Certificate> result = new ArrayList<>();
  result.add(queue.removeFirst());
  boolean foundTrustedCertificate = false;

  followIssuerChain:
  for (int c = 0; c < MAX_SIGNERS; c++) {
    X509Certificate toVerify = (X509Certificate) result.get(result.size() - 1);

    // If this cert has been signed by a trusted cert, use that. Add the trusted certificate to
    // the end of the chain unless it's already present. (That would happen if the first
    // certificate in the chain is itself a self-signed and trusted CA certificate.)
    X509Certificate trustedCert = trustRootIndex.findByIssuerAndSignature(toVerify);
    if (trustedCert != null) {
      if (result.size() > 1 || !toVerify.equals(trustedCert)) {
        result.add(trustedCert);
      }
      if (verifySignature(trustedCert, trustedCert)) {
        return result; // The self-signed cert is a root CA. We're done.
      }
      foundTrustedCertificate = true;
      continue;
    }

    // Search for the certificate in the chain that signed this certificate. This is typically
    // the next element in the chain, but it could be any element.
    for (Iterator<Certificate> i = queue.iterator(); i.hasNext(); ) {
      X509Certificate signingCert = (X509Certificate) i.next();
      if (verifySignature(toVerify, signingCert)) {
        i.remove();
        result.add(signingCert);
        continue followIssuerChain;
      }
    }

    // We've reached the end of the chain. If any cert in the chain is trusted, we're done.
    if (foundTrustedCertificate) {
      return result;
    }

    // The last link isn't trusted. Fail.
    throw new SSLPeerUnverifiedException(
        "Failed to find a trusted cert that signed " + toVerify);
  }

  throw new SSLPeerUnverifiedException("Certificate chain too long: " + result);
}
 
Example 20
Source File: ExplicitX509CertificateTrustEvaluator.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Evaluate trust.
 * 
 * @param untrustedCertificate the untrusted certificate to evaluate
 * @param trustedCertificate basis for trust
 * @return true if trust can be established, false otherwise
 */
public boolean validate(X509Certificate untrustedCertificate, X509Certificate trustedCertificate) {
    return untrustedCertificate.equals(trustedCertificate);
}