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

The following examples show how to use java.security.cert.X509Certificate#getSubjectX500Principal() . 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: UntrustedChecker.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void check(Certificate cert,
        Collection<String> unresolvedCritExts)
        throws CertPathValidatorException {

    X509Certificate currCert = (X509Certificate)cert;

    if (UntrustedCertificates.isUntrusted(currCert)) {
        if (debug != null) {
            debug.println("UntrustedChecker: untrusted certificate " +
                    currCert.getSubjectX500Principal());
        }

        throw new CertPathValidatorException(
            "Untrusted certificate: " + currCert.getSubjectX500Principal());
    }
}
 
Example 2
Source File: OkHostnameVerifier.java    From AndroidProjects with MIT License 6 votes vote down vote up
/** Returns true if {@code certificate} matches {@code hostname}. */
private boolean verifyHostname(String hostname, X509Certificate certificate) {
  hostname = hostname.toLowerCase(Locale.US);
  boolean hasDns = false;
  List<String> altNames = getSubjectAltNames(certificate, ALT_DNS_NAME);
  for (int i = 0, size = altNames.size(); i < size; i++) {
    hasDns = true;
    if (verifyHostname(hostname, altNames.get(i))) {
      return true;
    }
  }

  if (!hasDns) {
    X500Principal principal = certificate.getSubjectX500Principal();
    // RFC 2818 advises using the most specific name for matching.
    String cn = new DistinguishedNameParser(principal).findMostSpecific("cn");
    if (cn != null) {
      return verifyHostname(hostname, cn);
    }
  }

  return false;
}
 
Example 3
Source File: X509CertUtil.java    From portecle with GNU General Public License v2.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 parenthesis.
 *
 * @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 sSubjectCN = NameUtil.getCommonName(subject);

	// Could not get a subject CN - return blank
	if (sSubjectCN == null)
	{
		return "";
	}

	String sIssuerCN = NameUtil.getCommonName(issuer);

	// Self-signed certificate or could not get an issuer CN
	if (subject.equals(issuer) || sIssuerCN == null)
	{
		// Alias is the subject CN
		return sSubjectCN;
	}
	// else non-self-signed certificate
	// Alias is the subject CN followed by the issuer CN in parenthesis
	return MessageFormat.format("{0} ({1})", sSubjectCN, sIssuerCN);
}
 
Example 4
Source File: OkHostnameVerifier.java    From bluemix-parking-meter with MIT License 6 votes vote down vote up
/**
 * Returns true if {@code certificate} matches {@code hostName}.
 */
private boolean verifyHostName(String hostName, X509Certificate certificate) {
  hostName = hostName.toLowerCase(Locale.US);
  boolean hasDns = false;
  for (String altName : getSubjectAltNames(certificate, ALT_DNS_NAME)) {
    hasDns = true;
    if (verifyHostName(hostName, altName)) {
      return true;
    }
  }

  if (!hasDns) {
    X500Principal principal = certificate.getSubjectX500Principal();
    // RFC 2818 advises using the most specific name for matching.
    String cn = new DistinguishedNameParser(principal).findMostSpecific("cn");
    if (cn != null) {
      return verifyHostName(hostName, cn);
    }
  }

  return false;
}
 
Example 5
Source File: UntrustedChecker.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void check(Certificate cert,
        Collection<String> unresolvedCritExts)
        throws CertPathValidatorException {

    X509Certificate currCert = (X509Certificate)cert;

    if (UntrustedCertificates.isUntrusted(currCert)) {
        if (debug != null) {
            debug.println("UntrustedChecker: untrusted certificate " +
                    currCert.getSubjectX500Principal());
        }

        throw new CertPathValidatorException(
            "Untrusted certificate: " + currCert.getSubjectX500Principal());
    }
}
 
Example 6
Source File: RESTSecurityTokenServiceImpl.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
protected Principal getPrincipal() {
    // Try JAX-RS SecurityContext first
    if (securityContext != null && securityContext.getUserPrincipal() != null) {
        return securityContext.getUserPrincipal();
    }

    // Then try the CXF SecurityContext
    SecurityContext sc = (SecurityContext)messageContext.get(SecurityContext.class);
    if (sc != null && sc.getUserPrincipal() != null) {
        return sc.getUserPrincipal();
    }

    // Get the TLS client principal if no security context is set up
    X509Certificate clientCert = getTLSClientCertificate();
    if (clientCert != null) {
        return clientCert.getSubjectX500Principal();
    }

    return null;
}
 
Example 7
Source File: SymantecTLSPolicy.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
private static void checkNotBefore(LocalDate notBeforeDate,
        LocalDate distrustDate, X509Certificate anchor)
        throws ValidatorException {
    if (notBeforeDate.isAfter(distrustDate)) {
        throw new ValidatorException
            ("TLS Server certificate issued after " + distrustDate +
             " and anchored by a distrusted legacy Symantec root CA: "
             + anchor.getSubjectX500Principal(),
             ValidatorException.T_UNTRUSTED_CERT, anchor);
    }
}
 
Example 8
Source File: TrustedCertificateIndex.java    From cwac-netsecurity with Apache License 2.0 5 votes vote down vote up
public void index(TrustAnchor anchor) {
    X500Principal subject;
    X509Certificate cert = anchor.getTrustedCert();
    if (cert != null) {
        subject = cert.getSubjectX500Principal();
    } else {
        subject = anchor.getCA();
    }

    synchronized (subjectToTrustAnchors) {
        List<TrustAnchor> anchors = subjectToTrustAnchors.get(subject);
        if (anchors == null) {
            anchors = new ArrayList<TrustAnchor>(1);
            subjectToTrustAnchors.put(subject, anchors);
        } else {
            // Avoid indexing the same certificate multiple times
            if (cert != null) {
                for (TrustAnchor entry : anchors) {
                    if (cert.equals(entry.getTrustedCert())) {
                        return;
                    }
                }
            }
        }
        anchors.add(anchor);
    }
}
 
Example 9
Source File: TrustRootIndex.java    From AndroidProjects with MIT License 5 votes vote down vote up
public BasicTrustRootIndex(X509Certificate... caCerts) {
  subjectToCaCerts = new LinkedHashMap<>();
  for (X509Certificate caCert : caCerts) {
    X500Principal subject = caCert.getSubjectX500Principal();
    Set<X509Certificate> subjectCaCerts = subjectToCaCerts.get(subject);
    if (subjectCaCerts == null) {
      subjectCaCerts = new LinkedHashSet<>(1);
      subjectToCaCerts.put(subject, subjectCaCerts);
    }
    subjectCaCerts.add(caCert);
  }
}
 
Example 10
Source File: SymantecTLSPolicy.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void checkNotBefore(LocalDate notBeforeDate,
        LocalDate distrustDate, X509Certificate anchor)
        throws ValidatorException {
    if (notBeforeDate.isAfter(distrustDate)) {
        throw new ValidatorException
                ("TLS Server certificate issued after " + distrustDate +
                 " and anchored by a distrusted legacy Symantec root CA: "
                 + anchor.getSubjectX500Principal(),
                 ValidatorException.T_UNTRUSTED_CERT, anchor);
    }
}
 
Example 11
Source File: X509Utils.java    From Cybernet-VPN with GNU General Public License v3.0 5 votes vote down vote up
public static String getCertificateFriendlyName(X509Certificate cert) {
    X500Principal principal = cert.getSubjectX500Principal();
    byte[] encodedSubject = principal.getEncoded();
    String friendlyName = null;
    /* Hack so we do not have to ship a whole Spongy/bouncycastle */
    Exception exp = null;
    try {
        Class X509NameClass = Class.forName("com.android.org.bouncycastle.asn1.x509.X509Name");
        Method getInstance = X509NameClass.getMethod("getInstance", Object.class);
        Hashtable defaultSymbols = (Hashtable) X509NameClass.getField("DefaultSymbols").get(X509NameClass);
        if (!defaultSymbols.containsKey("1.2.840.113549.1.9.1")) defaultSymbols.put("1.2.840.113549.1.9.1", "eMail");
        Object subjectName = getInstance.invoke(X509NameClass, encodedSubject);
        Method toString = X509NameClass.getMethod("toString", boolean.class, Hashtable.class);
        friendlyName = (String) toString.invoke(subjectName, true, defaultSymbols);
    } catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException | IllegalAccessException | NoSuchFieldException e) {
        exp = e;
    }
    if (exp != null) VpnStatus.logException("Getting X509 Name from certificate", exp);
    /* Fallback if the reflection method did not work */
    if (friendlyName == null) friendlyName = principal.getName();
    // Really evil hack to decode email address
    // See: http://code.google.com/p/android/issues/detail?id=21531
    String[] parts = friendlyName.split(",");
    for (int i = 0; i < parts.length; i++) {
        String part = parts[i];
        if (part.startsWith("1.2.840.113549.1.9.1=#16")) {
            parts[i] = "email=" + ia5decode(part.replace("1.2.840.113549.1.9.1=#16", ""));
        }
    }
    friendlyName = TextUtils.join(",", parts);
    return friendlyName;
}
 
Example 12
Source File: PEMImporter.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
public static KeyStore loadTrustStore(File certificateChainFile)
    throws IOException, GeneralSecurityException
{
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(null, null);

    List<X509Certificate> certificateChain = readCertificateChain(certificateChainFile);
    for (X509Certificate certificate : certificateChain) {
        X500Principal principal = certificate.getSubjectX500Principal();
        keyStore.setCertificateEntry(principal.getName("RFC2253"), certificate);
    }
    return keyStore;
}
 
Example 13
Source File: SymantecTLSPolicy.java    From openjsse with GNU General Public License v2.0 5 votes vote down vote up
private static void checkNotBefore(LocalDate notBeforeDate,
        LocalDate distrustDate, X509Certificate anchor)
        throws ValidatorException {
    if (notBeforeDate.isAfter(distrustDate)) {
        throw new ValidatorException
                ("TLS Server certificate issued after " + distrustDate +
                 " and anchored by a distrusted legacy Symantec root CA: "
                 + anchor.getSubjectX500Principal(),
                 ValidatorException.T_UNTRUSTED_CERT, anchor);
    }
}
 
Example 14
Source File: XXnetManager.java    From Xndroid with GNU General Public License v3.0 5 votes vote down vote up
private static String getSubjectHash(String certPath){
        try {
            X509Certificate cert = (X509Certificate) CertificateFactory
                    .getInstance("X.509").generateCertificate(new FileInputStream(certPath));
            X500Principal subject = cert.getSubjectX500Principal();
            byte[] sumbytes = MessageDigest.getInstance("MD5").digest(subject.getEncoded());
            return Integer.toHexString(ByteBuffer.wrap(sumbytes).order(ByteOrder.LITTLE_ENDIAN).getInt());
        }catch (Exception e){
            LogUtils.e("get subject old hash fail", e);
        }
//        return "8da8b1b3";
        return null;
    }
 
Example 15
Source File: PemReader.java    From log4j2-elasticsearch with Apache License 2.0 5 votes vote down vote up
public static KeyStore loadTrustStore(FileInputStream certificateChainFile)
        throws IOException, GeneralSecurityException
{
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(null, null);

    List<X509Certificate> certificateChain = readCertificateChain(certificateChainFile);
    for (X509Certificate certificate : certificateChain) {
        X500Principal principal = certificate.getSubjectX500Principal();
        keyStore.setCertificateEntry(principal.getName("RFC2253"), certificate);
    }
    return keyStore;
}
 
Example 16
Source File: PemReader.java    From log4j2-elasticsearch with Apache License 2.0 5 votes vote down vote up
public static KeyStore loadTrustStore(FileInputStream certificateChainFile)
        throws IOException, GeneralSecurityException
{
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(null, null);

    List<X509Certificate> certificateChain = readCertificateChain(certificateChainFile);
    for (X509Certificate certificate : certificateChain) {
        X500Principal principal = certificate.getSubjectX500Principal();
        keyStore.setCertificateEntry(principal.getName("RFC2253"), certificate);
    }
    return keyStore;
}
 
Example 17
Source File: ForwardState.java    From jdk8u_jdk 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 18
Source File: CertPathValidatorUtilities.java    From RipplePower with Apache License 2.0 4 votes vote down vote up
protected static X500Principal getSubjectPrincipal(X509Certificate cert)
{
    return cert.getSubjectX500Principal();
}
 
Example 19
Source File: NameConstraintsExtension.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * check whether a certificate conforms to these NameConstraints.
 * This involves verifying that the subject name and subjectAltName
 * extension (critical or noncritical) is consistent with the permitted
 * subtrees state variables.  Also verify that the subject name and
 * subjectAltName extension (critical or noncritical) is consistent with
 * the excluded subtrees state variables.
 *
 * @param cert X509Certificate to be verified
 * @returns true if certificate verifies successfully
 * @throws IOException on error
 */
public boolean verify(X509Certificate cert) throws IOException {

    if (cert == null) {
        throw new IOException("Certificate is null");
    }

    // Calculate hasMin and hasMax booleans (if necessary)
    if (!minMaxValid) {
        calcMinMax();
    }

    if (hasMin) {
        throw new IOException("Non-zero minimum BaseDistance in"
                            + " name constraints not supported");
    }

    if (hasMax) {
        throw new IOException("Maximum BaseDistance in"
                            + " name constraints not supported");
    }

    X500Principal subjectPrincipal = cert.getSubjectX500Principal();
    X500Name subject = X500Name.asX500Name(subjectPrincipal);

    if (subject.isEmpty() == false) {
        if (verify(subject) == false) {
            return false;
        }
    }

    GeneralNames altNames = null;
    // extract altNames
    try {
        // extract extensions, if any, from certInfo
        // following returns null if certificate contains no extensions
        X509CertImpl certImpl = X509CertImpl.toImpl(cert);
        SubjectAlternativeNameExtension altNameExt =
            certImpl.getSubjectAlternativeNameExtension();
        if (altNameExt != null) {
            // extract altNames from extension; this call does not
            // return an IOException on null altnames
            altNames = altNameExt.get(
                    SubjectAlternativeNameExtension.SUBJECT_NAME);
        }
    } catch (CertificateException ce) {
        throw new IOException("Unable to extract extensions from " +
                    "certificate: " + ce.getMessage());
    }

    // If there are no subjectAlternativeNames, perform the special-case
    // check where if the subjectName contains any EMAILADDRESS
    // attributes, they must be checked against RFC822 constraints.
    // If that passes, we're fine.
    if (altNames == null) {
        return verifyRFC822SpecialCase(subject);
    }

    // verify each subjectAltName
    for (int i = 0; i < altNames.size(); i++) {
        GeneralNameInterface altGNI = altNames.get(i).getName();
        if (!verify(altGNI)) {
            return false;
        }
    }

    // All tests passed.
    return true;
}
 
Example 20
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;
}