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

The following examples show how to use java.security.cert.X509Certificate#getIssuerX500Principal() . 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: SecurityUtils.java    From RISE-V2G with MIT License 6 votes vote down vote up
/**
 * Iterates over the certificates stored in the truststore to verify the signature of the provided certificate
 * 
 * @param trustStoreFilename The relative path and file name of the truststore
 * @param certificate The certificate whose signature needs to be verified
 * @return True, if the provided certificate has been signed by one of the certificates in the 
 * 		   truststore, false otherwise
 */
public static boolean verifySignature(X509Certificate certificate, String trustStoreFilename) {
	KeyStore trustStore = SecurityUtils.getTrustStore(trustStoreFilename, GlobalValues.PASSPHRASE_FOR_CERTIFICATES_AND_KEYS.toString());
	X500Principal expectedIssuer = certificate.getIssuerX500Principal();
	
	try {
		Enumeration<String> aliases = trustStore.aliases();
		while (aliases.hasMoreElements()) {
			X509Certificate rootCA = (X509Certificate) trustStore.getCertificate(aliases.nextElement());
			if (rootCA.getSubjectX500Principal().getName().equals(expectedIssuer.getName()) &&
				verifySignature(certificate, rootCA)) return true;
		}
	} catch (KeyStoreException | NullPointerException e) {
		getLogger().error(e.getClass().getSimpleName() + " occurred while trying to verify trust " +
						  "status of certificate with distinguished name '" + 
						  certificate.getSubjectX500Principal().getName() + "' with truststore at " +
						  "location '" + trustStoreFilename + "'", e);
	}
	
	return false;
}
 
Example 2
Source File: X509CertUtil.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
/**
 * For a given X.509 certificate get a representative alias for it in a
 * KeyStore. For a self-signed certificate this will be the subject's common
 * name (if any). For a non-self-signed certificate it will be the subject's
 * common name followed by the issuer's common name in brackets. Aliases
 * will always be in lower case.
 *
 * @param cert
 *            The certificate
 * @return The alias or a blank string if none could be worked out
 */
public static String getCertificateAlias(X509Certificate cert) {
	X500Principal subject = cert.getSubjectX500Principal();
	X500Principal issuer = cert.getIssuerX500Principal();

	String subjectCn = X500NameUtils.extractCN(X500NameUtils.x500PrincipalToX500Name(subject));
	String issuerCn = X500NameUtils.extractCN(X500NameUtils.x500PrincipalToX500Name(issuer));

	if (StringUtils.isBlank(subjectCn)) {
		return "";
	}

	if (StringUtils.isBlank(issuerCn) || subjectCn.equals(issuerCn)) {
		return subjectCn;
	}

	return MessageFormat.format("{0} ({1})", subjectCn, issuerCn);
}
 
Example 3
Source File: TrustRootIndex.java    From styT with Apache License 2.0 6 votes vote down vote up
@Override public X509Certificate findByIssuerAndSignature(X509Certificate cert) {
  X500Principal issuer = cert.getIssuerX500Principal();
  Set<X509Certificate> subjectCaCerts = subjectToCaCerts.get(issuer);
  if (subjectCaCerts == null) return null;

  for (X509Certificate caCert : subjectCaCerts) {
    PublicKey publicKey = caCert.getPublicKey();
    try {
      cert.verify(publicKey);
      return caCert;
    } catch (Exception ignored) {
    }
  }

  return null;
}
 
Example 4
Source File: P11KeyStore.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * build [alias + issuer + serialNumber] string from a cert
 */
private String getID(String alias, X509Certificate cert) {
    X500Principal issuer = cert.getIssuerX500Principal();
    BigInteger serialNum = cert.getSerialNumber();

    return alias +
            ALIAS_SEP +
            issuer.getName(X500Principal.CANONICAL) +
            ALIAS_SEP +
            serialNum.toString();
}
 
Example 5
Source File: TrustedCertificateIndex.java    From cwac-netsecurity with Apache License 2.0 5 votes vote down vote up
public Set<TrustAnchor> findAllByIssuerAndSignature(X509Certificate cert) {
    X500Principal issuer = cert.getIssuerX500Principal();
    synchronized (subjectToTrustAnchors) {
        List<TrustAnchor> anchors = subjectToTrustAnchors.get(issuer);
        if (anchors == null) {
            return Collections.<TrustAnchor>emptySet();
        }

        Set<TrustAnchor> result = new HashSet<TrustAnchor>();
        for (TrustAnchor anchor : anchors) {
            try {
                PublicKey publicKey;
                X509Certificate caCert = anchor.getTrustedCert();
                if (caCert != null) {
                    publicKey = caCert.getPublicKey();
                } else {
                    publicKey = anchor.getCAPublicKey();
                }
                if (publicKey == null) {
                    continue;
                }
                cert.verify(publicKey);
                result.add(anchor);
            } catch (Exception ignored) {
            }
        }
        return result;
    }
}
 
Example 6
Source File: BasicChecker.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Internal method to check that cert has a valid DN to be next in a chain
 */
private void verifyNameChaining(X509Certificate cert)
    throws CertPathValidatorException
{
    if (prevSubject != null) {

        String msg = "subject/issuer name chaining";
        if (debug != null)
            debug.println("---checking " + msg + "...");

        X500Principal currIssuer = cert.getIssuerX500Principal();

        // reject null or empty issuer DNs
        if (X500Name.asX500Name(currIssuer).isEmpty()) {
            throw new CertPathValidatorException
                (msg + " check failed: " +
                 "empty/null issuer DN in certificate is invalid", null,
                 null, -1, PKIXReason.NAME_CHAINING);
        }

        if (!(currIssuer.equals(prevSubject))) {
            throw new CertPathValidatorException
                (msg + " check failed", null, null, -1,
                 PKIXReason.NAME_CHAINING);
        }

        if (debug != null)
            debug.println(msg + " verified.");
    }
}
 
Example 7
Source File: P11KeyStore.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * build [alias + issuer + serialNumber] string from a cert
 */
private String getID(String alias, X509Certificate cert) {
    X500Principal issuer = cert.getIssuerX500Principal();
    BigInteger serialNum = cert.getSerialNumber();

    return alias +
            ALIAS_SEP +
            issuer.getName(X500Principal.CANONICAL) +
            ALIAS_SEP +
            serialNum.toString();
}
 
Example 8
Source File: OcspCertificateValidator.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the issuer certificate.
 *
 * @param certificates certs
 * @return issuer cert
 */
private X509Certificate getIssuerCertificate(final X509Certificate[] certificates) {
    if (certificates.length > 1) {
        return certificates[1];
    } else if (certificates.length == 1) {
        final X509Certificate subjectCertificate = getSubjectCertificate(certificates);
        final X500Principal issuerPrincipal = subjectCertificate.getIssuerX500Principal();
        return trustedCAs.get(issuerPrincipal.getName());
    } else {
        return null;
    }
}
 
Example 9
Source File: P11KeyStore.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * build [alias + issuer + serialNumber] string from a cert
 */
private String getID(String alias, X509Certificate cert) {
    X500Principal issuer = cert.getIssuerX500Principal();
    BigInteger serialNum = cert.getSerialNumber();

    return alias +
            ALIAS_SEP +
            issuer.getName(X500Principal.CANONICAL) +
            ALIAS_SEP +
            serialNum.toString();
}
 
Example 10
Source File: ForwardState.java    From Bytecoder with Apache License 2.0 4 votes vote down vote up
/**
 * Update the state with the next certificate added to the path.
 *
 * @param cert the certificate which is used to update the state
 */
@Override
public void updateState(X509Certificate cert)
    throws CertificateException, IOException, CertPathValidatorException {

    if (cert == null)
        return;

    X509CertImpl icert = X509CertImpl.toImpl(cert);

    /* see if certificate key has null parameters */
    if (PKIX.isDSAPublicKeyWithoutParams(icert.getPublicKey())) {
        keyParamsNeededFlag = true;
    }

    /* update certificate */
    this.cert = icert;

    /* update issuer DN */
    issuerDN = cert.getIssuerX500Principal();

    if (!X509CertImpl.isSelfIssued(cert)) {

        /*
         * update traversedCACerts only if this is a non-self-issued
         * intermediate CA cert
         */
        if (!init && cert.getBasicConstraints() != -1) {
            traversedCACerts++;
        }
    }

    /* update subjectNamesTraversed only if this is the EE cert or if
       this cert is not self-issued */
    if (init || !X509CertImpl.isSelfIssued(cert)){
        X500Principal subjName = cert.getSubjectX500Principal();
        subjectNamesTraversed.add(X500Name.asX500Name(subjName));

        try {
            SubjectAlternativeNameExtension subjAltNameExt
                = icert.getSubjectAlternativeNameExtension();
            if (subjAltNameExt != null) {
                GeneralNames gNames = subjAltNameExt.get(
                        SubjectAlternativeNameExtension.SUBJECT_NAME);
                for (GeneralName gName : gNames.names()) {
                    subjectNamesTraversed.add(gName.getName());
                }
            }
        } catch (IOException e) {
            if (debug != null) {
                debug.println("ForwardState.updateState() unexpected "
                    + "exception");
                e.printStackTrace();
            }
            throw new CertPathValidatorException(e);
        }
    }

    init = false;
}
 
Example 11
Source File: X509CRLImpl.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Construct an X509IssuerSerial from an X509Certificate.
 */
X509IssuerSerial(X509Certificate cert) {
    this(cert.getIssuerX500Principal(), cert.getSerialNumber());
}
 
Example 12
Source File: ForwardState.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Update the state with the next certificate added to the path.
 *
 * @param cert the certificate which is used to update the state
 */
@Override
public void updateState(X509Certificate cert)
    throws CertificateException, IOException, CertPathValidatorException {

    if (cert == null)
        return;

    X509CertImpl icert = X509CertImpl.toImpl(cert);

    /* see if certificate key has null parameters */
    if (PKIX.isDSAPublicKeyWithoutParams(icert.getPublicKey())) {
        keyParamsNeededFlag = true;
    }

    /* update certificate */
    this.cert = icert;

    /* update issuer DN */
    issuerDN = cert.getIssuerX500Principal();

    if (!X509CertImpl.isSelfIssued(cert)) {

        /*
         * update traversedCACerts only if this is a non-self-issued
         * intermediate CA cert
         */
        if (!init && cert.getBasicConstraints() != -1) {
            traversedCACerts++;
        }
    }

    /* update subjectNamesTraversed only if this is the EE cert or if
       this cert is not self-issued */
    if (init || !X509CertImpl.isSelfIssued(cert)){
        X500Principal subjName = cert.getSubjectX500Principal();
        subjectNamesTraversed.add(X500Name.asX500Name(subjName));

        try {
            SubjectAlternativeNameExtension subjAltNameExt
                = icert.getSubjectAlternativeNameExtension();
            if (subjAltNameExt != null) {
                GeneralNames gNames = subjAltNameExt.get(
                        SubjectAlternativeNameExtension.SUBJECT_NAME);
                for (GeneralName gName : gNames.names()) {
                    subjectNamesTraversed.add(gName.getName());
                }
            }
        } catch (IOException e) {
            if (debug != null) {
                debug.println("ForwardState.updateState() unexpected "
                    + "exception");
                e.printStackTrace();
            }
            throw new CertPathValidatorException(e);
        }
    }

    init = false;
}
 
Example 13
Source File: X509CRLImpl.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Construct an X509IssuerSerial from an X509Certificate.
 */
X509IssuerSerial(X509Certificate cert) {
    this(cert.getIssuerX500Principal(), cert.getSerialNumber());
}
 
Example 14
Source File: ForwardState.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Update the state with the next certificate added to the path.
 *
 * @param cert the certificate which is used to update the state
 */
@Override
public void updateState(X509Certificate cert)
    throws CertificateException, IOException, CertPathValidatorException {

    if (cert == null)
        return;

    X509CertImpl icert = X509CertImpl.toImpl(cert);

    /* see if certificate key has null parameters */
    if (PKIX.isDSAPublicKeyWithoutParams(icert.getPublicKey())) {
        keyParamsNeededFlag = true;
    }

    /* update certificate */
    this.cert = icert;

    /* update issuer DN */
    issuerDN = cert.getIssuerX500Principal();

    if (!X509CertImpl.isSelfIssued(cert)) {

        /*
         * update traversedCACerts only if this is a non-self-issued
         * intermediate CA cert
         */
        if (!init && cert.getBasicConstraints() != -1) {
            traversedCACerts++;
        }
    }

    /* update subjectNamesTraversed only if this is the EE cert or if
       this cert is not self-issued */
    if (init || !X509CertImpl.isSelfIssued(cert)){
        X500Principal subjName = cert.getSubjectX500Principal();
        subjectNamesTraversed.add(X500Name.asX500Name(subjName));

        try {
            SubjectAlternativeNameExtension subjAltNameExt
                = icert.getSubjectAlternativeNameExtension();
            if (subjAltNameExt != null) {
                GeneralNames gNames = subjAltNameExt.get(
                        SubjectAlternativeNameExtension.SUBJECT_NAME);
                for (GeneralName gName : gNames.names()) {
                    subjectNamesTraversed.add(gName.getName());
                }
            }
        } catch (IOException e) {
            if (debug != null) {
                debug.println("ForwardState.updateState() unexpected "
                    + "exception");
                e.printStackTrace();
            }
            throw new CertPathValidatorException(e);
        }
    }

    init = false;
}
 
Example 15
Source File: ForwardState.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Update the state with the next certificate added to the path.
 *
 * @param cert the certificate which is used to update the state
 */
@Override
public void updateState(X509Certificate cert)
    throws CertificateException, IOException, CertPathValidatorException {

    if (cert == null)
        return;

    X509CertImpl icert = X509CertImpl.toImpl(cert);

    /* see if certificate key has null parameters */
    if (PKIX.isDSAPublicKeyWithoutParams(icert.getPublicKey())) {
        keyParamsNeededFlag = true;
    }

    /* update certificate */
    this.cert = icert;

    /* update issuer DN */
    issuerDN = cert.getIssuerX500Principal();

    if (!X509CertImpl.isSelfIssued(cert)) {

        /*
         * update traversedCACerts only if this is a non-self-issued
         * intermediate CA cert
         */
        if (!init && cert.getBasicConstraints() != -1) {
            traversedCACerts++;
        }
    }

    /* update subjectNamesTraversed only if this is the EE cert or if
       this cert is not self-issued */
    if (init || !X509CertImpl.isSelfIssued(cert)){
        X500Principal subjName = cert.getSubjectX500Principal();
        subjectNamesTraversed.add(X500Name.asX500Name(subjName));

        try {
            SubjectAlternativeNameExtension subjAltNameExt
                = icert.getSubjectAlternativeNameExtension();
            if (subjAltNameExt != null) {
                GeneralNames gNames = subjAltNameExt.get(
                        SubjectAlternativeNameExtension.SUBJECT_NAME);
                for (GeneralName gName : gNames.names()) {
                    subjectNamesTraversed.add(gName.getName());
                }
            }
        } catch (IOException e) {
            if (debug != null) {
                debug.println("ForwardState.updateState() unexpected "
                    + "exception");
                e.printStackTrace();
            }
            throw new CertPathValidatorException(e);
        }
    }

    init = false;
}
 
Example 16
Source File: X509CRLImpl.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Construct an X509IssuerSerial from an X509Certificate.
 */
X509IssuerSerial(X509Certificate cert) {
    this(cert.getIssuerX500Principal(), cert.getSerialNumber());
}
 
Example 17
Source File: X509CRLImpl.java    From Bytecoder with Apache License 2.0 4 votes vote down vote up
/**
 * Construct an X509IssuerSerial from an X509Certificate.
 */
X509IssuerSerial(X509Certificate cert) {
    this(cert.getIssuerX500Principal(), cert.getSerialNumber());
}
 
Example 18
Source File: FluentKeySigner.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public FluentKeySigner(X509Certificate caCert, KeyPair caKey) {
    this(caCert.getIssuerX500Principal(), caKey);
    authorityCertificate(caCert);
}
 
Example 19
Source File: CertPathValidatorUtilities.java    From RipplePower with Apache License 2.0 4 votes vote down vote up
/**
 * Fetches complete CRLs according to RFC 3280.
 *
 * @param dp          The distribution point for which the complete CRL
 * @param cert        The <code>X509Certificate</code> or
 *                    {@link org.ripple.bouncycastle.x509.X509AttributeCertificate} for
 *                    which the CRL should be searched.
 * @param currentDate The date for which the delta CRLs must be valid.
 * @param paramsPKIX  The extended PKIX parameters.
 * @return A <code>Set</code> of <code>X509CRL</code>s with complete
 *         CRLs.
 * @throws AnnotatedException if an exception occurs while picking the CRLs
 * or no CRLs are found.
 */
protected static Set getCompleteCRLs(DistributionPoint dp, Object cert,
                                     Date currentDate, ExtendedPKIXParameters paramsPKIX)
    throws AnnotatedException
{
    X509CRLStoreSelector crlselect = new X509CRLStoreSelector();
    try
    {
        Set issuers = new HashSet();
        if (cert instanceof X509AttributeCertificate)
        {
            issuers.add(((X509AttributeCertificate)cert)
                .getIssuer().getPrincipals()[0]);
        }
        else
        {
            issuers.add(getEncodedIssuerPrincipal(cert));
        }
        CertPathValidatorUtilities.getCRLIssuersFromDistributionPoint(dp, issuers, crlselect, paramsPKIX);
    }
    catch (AnnotatedException e)
    {
        throw new AnnotatedException(
            "Could not get issuer information from distribution point.", e);
    }
    if (cert instanceof X509Certificate)
    {
        crlselect.setCertificateChecking((X509Certificate)cert);
    }
    else if (cert instanceof X509AttributeCertificate)
    {
        crlselect.setAttrCertificateChecking((X509AttributeCertificate)cert);
    }


    crlselect.setCompleteCRLEnabled(true);

    Set crls = CRL_UTIL.findCRLs(crlselect, paramsPKIX, currentDate);

    if (crls.isEmpty())
    {
        if (cert instanceof X509AttributeCertificate)
        {
            X509AttributeCertificate aCert = (X509AttributeCertificate)cert;

            throw new AnnotatedException("No CRLs found for issuer \"" + aCert.getIssuer().getPrincipals()[0] + "\"");
        }
        else
        {
            X509Certificate xCert = (X509Certificate)cert;

            throw new AnnotatedException("No CRLs found for issuer \"" + xCert.getIssuerX500Principal() + "\"");
        }
    }
    return crls;
}
 
Example 20
Source File: CRLUtils.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private static X509Certificate findCRLSignatureCertificateInTruststore(KeycloakSession session, X509Certificate[] certs, X500Principal crlIssuerPrincipal) throws GeneralSecurityException {
    TruststoreProvider truststoreProvider = session.getProvider(TruststoreProvider.class);
    if (truststoreProvider == null || truststoreProvider.getTruststore() == null) {
        throw new GeneralSecurityException("Truststore not available");
    }

    Map<X500Principal, X509Certificate> rootCerts = truststoreProvider.getRootCertificates();
    Map<X500Principal, X509Certificate> intermediateCerts = truststoreProvider.getIntermediateCertificates();

    X509Certificate crlSignatureCertificate = intermediateCerts.get(crlIssuerPrincipal);
    if (crlSignatureCertificate == null) {
        crlSignatureCertificate = rootCerts.get(crlIssuerPrincipal);
    }

    if (crlSignatureCertificate == null) {
        throw new GeneralSecurityException("Not available certificate for CRL issuer '" + crlIssuerPrincipal + "' in the truststore, nor in the CA chain");
    } else {
        log.tracef("Found CRL issuer certificate with subject '%s' in the truststore. Verifying trust anchor", crlIssuerPrincipal);
    }

    // Check if CRL issuer has trust anchor with the checked certificate (See https://tools.ietf.org/html/rfc5280#section-6.3.3 , paragraph (f))
    Set<X500Principal> certificateCAPrincipals = Arrays.asList(certs).stream()
            .map(X509Certificate::getSubjectX500Principal)
            .collect(Collectors.toSet());

    // Remove the checked certificate itself
    certificateCAPrincipals.remove(certs[0].getSubjectX500Principal());

    X509Certificate currentCRLAnchorCertificate = crlSignatureCertificate;
    X500Principal currentCRLAnchorPrincipal = crlIssuerPrincipal;
    while (true) {
        if (certificateCAPrincipals.contains(currentCRLAnchorPrincipal)) {
            log.tracef("Found trust anchor of the CRL issuer '%s' in the CA chain. Anchor is '%s'", crlIssuerPrincipal, currentCRLAnchorPrincipal);
            break;
        }

        // Try to see the anchor
        currentCRLAnchorPrincipal = currentCRLAnchorCertificate.getIssuerX500Principal();

        currentCRLAnchorCertificate = intermediateCerts.get(currentCRLAnchorPrincipal);
        if (currentCRLAnchorCertificate == null) {
            currentCRLAnchorCertificate = rootCerts.get(currentCRLAnchorPrincipal);
        }
        if (currentCRLAnchorCertificate == null) {
            throw new GeneralSecurityException("Certificate for CRL issuer '" + crlIssuerPrincipal + "' available in the truststore, but doesn't have trust anchors with the CA chain.");
        }
    }

    return crlSignatureCertificate;
}