Example usage for java.security.cert X509Certificate getSubjectAlternativeNames

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

Introduction

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

Prototype

public Collection<List<?>> getSubjectAlternativeNames() throws CertificateParsingException 

Source Link

Document

Gets an immutable collection of subject alternative names from the SubjectAltName extension, (OID = 2.5.29.17).

Usage

From source file:com.newrelic.agent.deps.org.apache.http.conn.ssl.DefaultHostnameVerifier.java

static List<String> extractSubjectAlts(final X509Certificate cert, final int subjectType) {
    Collection<List<?>> c = null;
    try {/*from   ww w.j  a  va2 s  .  co  m*/
        c = cert.getSubjectAlternativeNames();
    } catch (final CertificateParsingException ignore) {
    }
    List<String> subjectAltList = null;
    if (c != null) {
        for (final List<?> aC : c) {
            final List<?> list = aC;
            final int type = ((Integer) list.get(0)).intValue();
            if (type == subjectType) {
                final String s = (String) list.get(1);
                if (subjectAltList == null) {
                    subjectAltList = new ArrayList<String>();
                }
                subjectAltList.add(s);
            }
        }
    }
    return subjectAltList;
}

From source file:org.opensaml.xml.security.x509.X509Util.java

/**
 * Gets the list of alternative names of a given name type.
 * /*from w  w  w . ja  v a2  s. c o m*/
 * @param certificate the certificate to extract the alternative names from
 * @param nameTypes the name types
 * 
 * @return the alt names, of the given type, within the cert
 */
public static List getAltNames(X509Certificate certificate, Integer[] nameTypes) {
    if (certificate == null) {
        return null;
    }

    List<Object> names = new LinkedList<Object>();
    try {
        Collection<List<?>> altNames = certificate.getSubjectAlternativeNames();
        if (altNames != null) {
            // 0th position represents the alt name type
            // 1st position contains the alt name data
            List altName;
            for (Iterator<List<?>> nameIterator = altNames.iterator(); nameIterator.hasNext();) {
                altName = nameIterator.next();
                for (int i = 0; i < nameTypes.length; i++) {
                    if (altName.get(0).equals(nameTypes[i])) {
                        names.add(altName.get(1));
                        break;
                    }
                }
            }
        }
    } catch (CertificateParsingException e1) {
        log.error("Encountered an problem trying to extract Subject Alternate "
                + "Name from supplied certificate: " + e1);
    }

    return names;
}

From source file:de.vanita5.twittnuker.util.net.ssl.AbstractCheckSignatureVerifier.java

/**
 * Extracts the array of SubjectAlt DNS or IP names from an X509Certificate.
 * Returns null if there aren't any.//from   www .jav a2 s . c  o  m
 *
 * @param cert X509Certificate
 * @param hostname
 * @return Array of SubjectALT DNS or IP names stored in the certificate.
 */
private static String[] getSubjectAlts(final X509Certificate cert, final String hostname) {
    final int subjectType;
    if (isIPAddress(hostname)) {
        subjectType = 7;
    } else {
        subjectType = 2;
    }

    final LinkedList<String> subjectAltList = new LinkedList<String>();
    Collection<List<?>> c = null;
    try {
        c = cert.getSubjectAlternativeNames();
    } catch (final CertificateParsingException cpe) {
    }
    if (c != null) {
        for (final List<?> aC : c) {
            final List<?> list = aC;
            final int type = ((Integer) list.get(0)).intValue();
            if (type == subjectType) {
                final String s = (String) list.get(1);
                subjectAltList.add(s);
            }
        }
    }
    if (!subjectAltList.isEmpty()) {
        final String[] subjectAlts = new String[subjectAltList.size()];
        subjectAltList.toArray(subjectAlts);
        return subjectAlts;
    } else
        return null;
}

From source file:com.epam.reportportal.apache.http.conn.ssl.AbstractVerifier.java

/**
 * Extracts the array of SubjectAlt DNS or IP names from an X509Certificate.
 * Returns null if there aren't any./*from  www.j  ava2s.c o  m*/
 *
 * @param cert X509Certificate
 * @param hostname
 * @return Array of SubjectALT DNS or IP names stored in the certificate.
 */
private static String[] getSubjectAlts(final X509Certificate cert, final String hostname) {
    final int subjectType;
    if (isIPAddress(hostname)) {
        subjectType = 7;
    } else {
        subjectType = 2;
    }

    final LinkedList<String> subjectAltList = new LinkedList<String>();
    Collection<List<?>> c = null;
    try {
        c = cert.getSubjectAlternativeNames();
    } catch (final CertificateParsingException cpe) {
    }
    if (c != null) {
        for (final List<?> aC : c) {
            final List<?> list = aC;
            final int type = ((Integer) list.get(0)).intValue();
            if (type == subjectType) {
                final String s = (String) list.get(1);
                subjectAltList.add(s);
            }
        }
    }
    if (!subjectAltList.isEmpty()) {
        final String[] subjectAlts = new String[subjectAltList.size()];
        subjectAltList.toArray(subjectAlts);
        return subjectAlts;
    } else {
        return null;
    }
}

From source file:org.apache.nifi.registry.security.util.CertificateUtils.java

/**
 * Returns a list of subject alternative names. Any name that is represented as a String by X509Certificate.getSubjectAlternativeNames() is converted to lowercase and returned.
 *
 * @param certificate a certificate//ww w. j ava 2  s.c  o  m
 * @return a list of subject alternative names; list is never null
 * @throws CertificateParsingException if parsing the certificate failed
 */
public static List<String> getSubjectAlternativeNames(final X509Certificate certificate)
        throws CertificateParsingException {

    final Collection<List<?>> altNames = certificate.getSubjectAlternativeNames();
    if (altNames == null) {
        return new ArrayList<>();
    }

    final List<String> result = new ArrayList<>();
    for (final List<?> generalName : altNames) {
        /**
         * generalName has the name type as the first element a String or byte array for the second element. We return any general names that are String types.
         *
         * We don't inspect the numeric name type because some certificates incorrectly put IPs and DNS names under the wrong name types.
         */
        final Object value = generalName.get(1);
        if (value instanceof String) {
            result.add(((String) value).toLowerCase());
        }

    }

    return result;
}

From source file:net.java.sip.communicator.impl.certificate.CertificateServiceImpl.java

/**
 * Gets the SAN (Subject Alternative Name) of the specified type.
 *
 * @param cert the certificate to extract from
 * @param altNameType The type to be returned
 * @return SAN of the type//w ww .  ja  v  a 2 s . c  o m
 *
 * <PRE>
 * GeneralName ::= CHOICE {
 *                 otherName                   [0]   OtherName,
 *                 rfc822Name                  [1]   IA5String,
 *                 dNSName                     [2]   IA5String,
 *                 x400Address                 [3]   ORAddress,
 *                 directoryName               [4]   Name,
 *                 ediPartyName                [5]   EDIPartyName,
 *                 uniformResourceIdentifier   [6]   IA5String,
 *                 iPAddress                   [7]   OCTET STRING,
 *                 registeredID                [8]   OBJECT IDENTIFIER
 *              }
 * <PRE>
 */
private static Iterable<String> getSubjectAltNames(X509Certificate cert, int altNameType) {
    Collection<List<?>> altNames = null;
    try {
        altNames = cert.getSubjectAlternativeNames();
    } catch (CertificateParsingException e) {
        return Collections.emptyList();
    }

    List<String> matchedAltNames = new LinkedList<String>();
    for (List<?> item : altNames) {
        if (item.contains(altNameType)) {
            Integer type = (Integer) item.get(0);
            if (type.intValue() == altNameType)
                matchedAltNames.add((String) item.get(1));
        }
    }
    return matchedAltNames;
}

From source file:org.commonjava.util.jhttpc.INTERNAL.util.SSLUtils.java

public static void extractAliases(Certificate certificate, Set<String> aliases)
        throws CertificateParsingException {
    Logger logger = LoggerFactory.getLogger(SSLUtils.class);

    X509Certificate cert = (X509Certificate) certificate;
    //        logger.debug( "Extracting aliases from:\n\n{}\n\n", cert );

    X500Principal x500Principal = cert.getSubjectX500Principal();
    X500Name x500Name = new X500Name(x500Principal.getName(X500Principal.RFC1779));
    logger.trace("Certificate X.500 name: '{}'", x500Name.toString());

    RDN[] matchingRDNs = x500Name.getRDNs(BCStyle.CN);
    if (matchingRDNs != null && matchingRDNs.length > 0) {
        RDN cn = matchingRDNs[0];//  ww w.j a  va 2  s .  c  om
        AttributeTypeAndValue typeAndValue = cn.getFirst();
        if (typeAndValue != null) {
            String alias = IETFUtils.valueToString(typeAndValue.getValue());
            logger.trace("Found certificate alias: '{}'", alias);
            aliases.add(alias);
        }
    }

    Collection<List<?>> subjectAlternativeNames = cert.getSubjectAlternativeNames();
    if (subjectAlternativeNames != null) {
        for (List<?> names : subjectAlternativeNames) {
            if (names.size() > 1 && (DNSNAME_TYPE.equals(names.get(0)))) {
                String alias = (String) names.get(1);
                logger.trace("Found subjectAlternativeName: '{}'", alias);
                aliases.add(alias);
            }
        }
    } else {
        logger.debug("NO SubjectAlternativeNames available!");
    }
}

From source file:ua.pp.msk.cliqr.CliQrHostnameVerifier.java

@Override
public final void verify(String host, X509Certificate cert) throws SSLException {
    Principal subjectDN = cert.getSubjectDN();
    try {//from ww w  . j  av  a 2s. c om
        Collection<List<?>> subjectAlternativeNames = cert.getSubjectAlternativeNames();
        if (subjectAlternativeNames != null) {
            subjectAlternativeNames.stream().map((subList) -> {
                logger.debug("Processing alternative");
                return subList;
            }).map((subList) -> {
                StringBuilder sb = new StringBuilder();
                subList.stream().forEach((o) -> {
                    sb.append(o.toString()).append(", ");
                });
                return sb;
            }).forEach((sb) -> {
                logger.debug(sb.toString());
            });
        }
    } catch (CertificateParsingException ex) {
        logger.info("It is useful to ignore such king of exceptions", ex);
    }
    logger.debug("Subject distiguished name: " + subjectDN.getName());
}

From source file:org.jasig.cas.adaptors.x509.authentication.principal.X509SubjectAlternativeNameUPNPrincipalResolver.java

/**
 * Retrieves Subject Alternative Name UPN extension as a principal id String.
 *
 * @param certificate X.509 certificate credential.
 *
 * @return Resolved principal ID or null if no SAN UPN extension is available in provided certificate.
 *
 * @see AbstractX509PrincipalResolver#resolvePrincipalInternal(java.security.cert.X509Certificate)
 * @see <a href="http://docs.oracle.com/javase/7/docs/api/java/security/cert/X509Certificate.html#getSubjectAlternativeNames()">
 *     X509Certificate#getSubjectAlternativeNames</a>
 *///from  w  ww. jav  a2s  .  c  o m
@Override
protected String resolvePrincipalInternal(final X509Certificate certificate) {
    logger.debug("Resolving principal from Subject Alternative Name UPN for {}", certificate);
    try {
        final Collection<List<?>> subjectAltNames = certificate.getSubjectAlternativeNames();
        if (subjectAltNames != null) {
            for (final List<?> sanItem : subjectAltNames) {
                final ASN1Sequence seq = getAltnameSequence(sanItem);
                final String upnString = getUPNStringFromSequence(seq);
                if (upnString != null) {
                    return upnString;
                }
            }
        }
    } catch (final CertificateParsingException e) {
        logger.error(
                "Error is encountered while trying to retrieve subject alternative names collection from certificate",
                e);
        logger.debug("Returning null principal id...");
        return null;
    }
    logger.debug("Returning null principal id...");
    return null;
}

From source file:org.waveprotocol.wave.crypto.WaveSignatureVerifier.java

/**
 * Returns true if the authority given matches any of the
 * SubjectAlternativeNames present in the certificate, false otherwise.
 *//* w w  w  .  j a v a  2 s . c om*/
private boolean authorityMatchesSubjectAlternativeNames(String authority, X509Certificate certificate) {

    Collection<List<?>> subjAltNames = null;
    try {
        subjAltNames = certificate.getSubjectAlternativeNames();
    } catch (CertificateParsingException e) {

        // This is a bit strange - it means that the AubjectAlternativeNames
        // extension wasn't properly encoded in this cert. We'll leave subjAltNames null.
    }

    if (subjAltNames == null) {
        return false;
    }

    for (List<?> altName : subjAltNames) {

        Integer nameType = (Integer) altName.get(0);

        // We're only interested in alternative names that denote domain names.
        if (!ALT_NAME_TYPE_DNS.equals(nameType)) {
            continue;
        }

        String dnsName = (String) altName.get(1);
        if (authority.equals(dnsName)) {
            return true;
        }
    }

    // None of the names matched.
    return false;
}