Example usage for org.bouncycastle.asn1.x509 GeneralName getName

List of usage examples for org.bouncycastle.asn1.x509 GeneralName getName

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 GeneralName getName.

Prototype

public ASN1Encodable getName() 

Source Link

Usage

From source file:net.sf.portecle.crypto.X509Ext.java

License:Open Source License

/**
 * Get the supplied general name as a string ([general name type]=[general name]).
 * //from www. j a  va  2  s .co  m
 * <pre>
 * GeneralName ::= CHOICE {
 *     otherName                       [0]     OtherName,
 *     rfc822Name                      [1]     IA5String, x
 *     dNSName                         [2]     IA5String, x
 *     x400Address                     [3]     ORAddress,
 *     directoryName                   [4]     Name, x
 *     ediPartyName                    [5]     EDIPartyName,
 *     uniformResourceIdentifier       [6]     IA5String, x
 *     iPAddress                       [7]     OCTET STRING, x
 *     registeredID                    [8]     OBJECT IDENTIFIER x }
 * OtherName ::= SEQUENCE {
 *     type-id    OBJECT IDENTIFIER,
 *     value      [0] EXPLICIT ANY DEFINED BY type-id }
 * EDIPartyName ::= SEQUENCE {
 *     nameAssigner            [0]     DirectoryString OPTIONAL,
 *     partyName               [1]     DirectoryString }
 * DirectoryString ::= CHOICE {
 *     teletexString           TeletexString (SIZE (1..maxSize),
 *     printableString         PrintableString (SIZE (1..maxSize)),
 *     universalString         UniversalString (SIZE (1..maxSize)),
 *     utf8String              UTF8String (SIZE (1.. MAX)),
 *     bmpString               BMPString (SIZE(1..maxSIZE)) }
 * </pre>
 * 
 * @param generalName The general name
 * @return General name string
 * @throws IOException
 */
private String getGeneralNameString(GeneralName generalName, LinkClass linkClass) throws IOException {
    StringBuilder strBuff = new StringBuilder();
    int tagNo = generalName.getTagNo();

    switch (tagNo) {
    case GeneralName.otherName:
        ASN1Sequence other = (ASN1Sequence) generalName.getName();
        String sOid = ((ASN1ObjectIdentifier) other.getObjectAt(0)).getId();
        String sVal = stringify(other.getObjectAt(1));
        try {
            strBuff.append(RB.getString(sOid));
        } catch (MissingResourceException e) {
            strBuff.append(MessageFormat.format(RB.getString("GeneralName." + tagNo), sOid));
        }
        strBuff.append(": ");
        strBuff.append(sVal);
        break;

    case GeneralName.rfc822Name:
        String sRfc822 = generalName.getName().toString();
        String urlEnc = URLEncoder.encode(sRfc822, "UTF-8");
        strBuff.append(RB.getString("GeneralName." + tagNo));
        strBuff.append(": ");
        strBuff.append(getLink("mailto:" + urlEnc, escapeHtml(sRfc822), null));
        break;

    case GeneralName.dNSName:
    case GeneralName.registeredID:
    case GeneralName.x400Address: // TODO: verify formatting
    case GeneralName.ediPartyName: // TODO: verify formatting
        strBuff.append(RB.getString("GeneralName." + tagNo));
        strBuff.append(": ");
        strBuff.append(escapeHtml(generalName.getName()));
        break;

    case GeneralName.directoryName:
        ASN1Encodable name = generalName.getName();
        strBuff.append(RB.getString("GeneralName." + tagNo));
        strBuff.append(": ");
        // TODO: make E=foo@bar.com mail links
        strBuff.append(escapeHtml(name));
        break;

    case GeneralName.uniformResourceIdentifier:
        String sUri = generalName.getName().toString();
        strBuff.append(RB.getString("GeneralName." + tagNo));
        strBuff.append(": ");
        strBuff.append(getLink(sUri, escapeHtml(sUri), linkClass));
        break;

    case GeneralName.iPAddress:
        ASN1OctetString ipAddress = (ASN1OctetString) generalName.getName();

        byte[] bIpAddress = ipAddress.getOctets();

        // Output the IP Address components one at a time separated by dots
        StringBuilder sbIpAddress = new StringBuilder();

        for (int iCnt = 0, bl = bIpAddress.length; iCnt < bl; iCnt++) {
            // Convert from (possibly negative) byte to positive int
            sbIpAddress.append(bIpAddress[iCnt] & 0xFF);
            if ((iCnt + 1) < bIpAddress.length) {
                sbIpAddress.append('.');
            }
        }

        strBuff.append(RB.getString("GeneralName." + tagNo));
        strBuff.append(": ");
        strBuff.append(escapeHtml(sbIpAddress));
        break;

    default: // Unsupported general name type
        strBuff.append(
                MessageFormat.format(RB.getString("UnrecognizedGeneralNameType"), generalName.getTagNo()));
        strBuff.append(": ");
        strBuff.append(escapeHtml(generalName.getName()));
        break;
    }

    return strBuff.toString();
}

From source file:net.wstech2.me.httpsclient.CertificateValidatorUtils.java

License:Apache License

/**
 * Retrieves the list of alternative DNS names for this certificate, if any.
 * //from   ww w.  j  a v  a2  s  .  com
 * @param cert
 *            The certificate from which the issuer name is to the
 *            extracted.
 * @return A list with all alternative DNS names included in the
 *         certificate.
 * @throws IOException
 */
public static List extractSubjectAlternativeNameList(org.bouncycastle.asn1.x509.Certificate cert)
        throws IOException {
    List dnsNames = new ArrayList();
    dnsNames.add(CertificateValidatorUtils.extractCommonName(cert, true));
    Extension subjectAlternativeName = cert.getTBSCertificate().getExtensions()
            .getExtension(Extension.subjectAlternativeName);
    if (subjectAlternativeName == null) {
        return dnsNames;
    }
    ASN1OctetString oct = subjectAlternativeName.getExtnValue();
    ASN1InputStream extIn = new ASN1InputStream(new ByteArrayInputStream(oct.getOctets()));
    GeneralNames gn = GeneralNames.getInstance(extIn.readObject());
    extIn.close();
    ASN1Sequence sq = (ASN1Sequence) gn.toASN1Primitive();
    for (int i = 0; i != sq.size(); i++) {
        GeneralName n = GeneralName.getInstance(sq.getObjectAt(i));
        dnsNames.add(n.getName().toString());

    }
    return dnsNames;
}

From source file:org.apache.jmeter.assertions.SMIMEAssertion.java

License:Apache License

/**
 * Extract email addresses from a certificate
 * /*from   w  w  w .j av  a 2  s . c  o m*/
 * @param cert the X509 certificate holder
 * @return a List of all email addresses found
 * @throws CertificateException
 */
private static List<String> getEmailFromCert(X509CertificateHolder cert) throws CertificateException {
    List<String> res = new ArrayList<>();

    X500Name subject = cert.getSubject();
    for (RDN emails : subject.getRDNs(BCStyle.EmailAddress)) {
        for (AttributeTypeAndValue emailAttr : emails.getTypesAndValues()) {
            log.debug("Add email from RDN: " + IETFUtils.valueToString(emailAttr.getValue()));
            res.add(IETFUtils.valueToString(emailAttr.getValue()));
        }
    }

    Extension subjectAlternativeNames = cert.getExtension(Extension.subjectAlternativeName);
    if (subjectAlternativeNames != null) {
        for (GeneralName name : GeneralNames.getInstance(subjectAlternativeNames.getParsedValue()).getNames()) {
            if (name.getTagNo() == GeneralName.rfc822Name) {
                String email = IETFUtils.valueToString(name.getName());
                log.debug("Add email from subjectAlternativeName: " + email);
                res.add(email);
            }
        }
    }

    return res;
}

From source file:org.apache.nifi.toolkit.tls.util.TlsHelperTest.java

License:Apache License

private List<String> extractSanFromCsr(JcaPKCS10CertificationRequest csr) {
    List<String> sans = new ArrayList<>();
    Attribute[] certAttributes = csr.getAttributes();
    for (Attribute attribute : certAttributes) {
        if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
            GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
            GeneralName[] names = gns.getNames();
            for (GeneralName name : names) {
                logger.info("Type: " + name.getTagNo() + " | Name: " + name.getName());
                String title = "";
                if (name.getTagNo() == GeneralName.dNSName) {
                    title = "DNS";
                } else if (name.getTagNo() == GeneralName.iPAddress) {
                    title = "IP Address";
                    // name.toASN1Primitive();
                } else if (name.getTagNo() == GeneralName.otherName) {
                    title = "Other Name";
                }// w  ww  .  j  av a 2  s  .  co  m
                sans.add(title + ": " + name.getName());
            }
        }
    }

    return sans;
}

From source file:org.apache.synapse.transport.certificatevalidation.crl.CRLVerifier.java

License:Apache License

/**
 * Extracts all CRL distribution point URLs from the "CRL Distribution Point"
 * extension in a X.509 certificate. If CRL distribution point extension is
 * unavailable, returns an empty list.//from w w w . j a  va 2 s . co  m
 */
private List<String> getCrlDistributionPoints(X509Certificate cert) throws CertificateVerificationException {

    //Gets the DER-encoded OCTET string for the extension value for CRLDistributionPoints
    byte[] crlDPExtensionValue = cert.getExtensionValue(X509Extensions.CRLDistributionPoints.getId());
    if (crlDPExtensionValue == null)
        throw new CertificateVerificationException("Certificate doesn't have CRL Distribution points");
    //crlDPExtensionValue is encoded in ASN.1 format.
    ASN1InputStream asn1In = new ASN1InputStream(crlDPExtensionValue);
    //DER (Distinguished Encoding Rules) is one of ASN.1 encoding rules defined in ITU-T X.690, 2002, specification.
    //ASN.1 encoding rules can be used to encode any data object into a binary file. Read the object in octets.
    CRLDistPoint distPoint;
    try {
        DEROctetString crlDEROctetString = (DEROctetString) asn1In.readObject();
        //Get Input stream in octets
        ASN1InputStream asn1InOctets = new ASN1InputStream(crlDEROctetString.getOctets());
        DERObject crlDERObject = asn1InOctets.readObject();
        distPoint = CRLDistPoint.getInstance(crlDERObject);
    } catch (IOException e) {
        throw new CertificateVerificationException("Cannot read certificate to get CRL urls", e);
    }

    List<String> crlUrls = new ArrayList<String>();
    //Loop through ASN1Encodable DistributionPoints
    for (DistributionPoint dp : distPoint.getDistributionPoints()) {
        //get ASN1Encodable DistributionPointName
        DistributionPointName dpn = dp.getDistributionPoint();
        if (dpn != null && dpn.getType() == DistributionPointName.FULL_NAME) {
            //Create ASN1Encodable General Names
            GeneralName[] genNames = GeneralNames.getInstance(dpn.getName()).getNames();
            // Look for a URI
            //todo: May be able to check for OCSP url specifically.
            for (GeneralName genName : genNames) {
                if (genName.getTagNo() == GeneralName.uniformResourceIdentifier) {
                    //DERIA5String contains an ascii string.
                    //A IA5String is a restricted character string type in the ASN.1 notation
                    String url = DERIA5String.getInstance(genName.getName()).getString().trim();
                    crlUrls.add(url);
                }
            }
        }
    }

    if (crlUrls.isEmpty())
        throw new CertificateVerificationException("Cant get CRL urls from certificate");

    return crlUrls;
}

From source file:org.apache.synapse.transport.certificatevalidation.ocsp.OCSPVerifier.java

License:Apache License

/**
 * Authority Information Access (AIA) is a non-critical extension in an X509 Certificate. This contains the
 * URL of the OCSP endpoint if one is available.
 * TODO: This might contain non OCSP urls as well. Handle this.
 *
 * @param cert is the certificate/*from  w  ww.ja v  a  2 s  . c om*/
 * @return a lit of URLs in AIA extension of the certificate which will hopefully contain an OCSP endpoint.
 * @throws CertificateVerificationException
 *
 */
private List<String> getAIALocations(X509Certificate cert) throws CertificateVerificationException {

    //Gets the DER-encoded OCTET string for the extension value for Authority information access Points
    byte[] aiaExtensionValue = cert.getExtensionValue(X509Extensions.AuthorityInfoAccess.getId());
    if (aiaExtensionValue == null)
        throw new CertificateVerificationException(
                "Certificate Doesnt have Authority Information Access points");
    //might have to pass an ByteArrayInputStream(aiaExtensionValue)
    ASN1InputStream asn1In = new ASN1InputStream(aiaExtensionValue);
    AuthorityInformationAccess authorityInformationAccess;

    try {
        DEROctetString aiaDEROctetString = (DEROctetString) (asn1In.readObject());
        ASN1InputStream asn1Inoctets = new ASN1InputStream(aiaDEROctetString.getOctets());
        ASN1Sequence aiaASN1Sequence = (ASN1Sequence) asn1Inoctets.readObject();
        authorityInformationAccess = new AuthorityInformationAccess(aiaASN1Sequence);
    } catch (IOException e) {
        throw new CertificateVerificationException("Cannot read certificate to get OSCP urls", e);
    }

    List<String> ocspUrlList = new ArrayList<String>();
    AccessDescription[] accessDescriptions = authorityInformationAccess.getAccessDescriptions();
    for (AccessDescription accessDescription : accessDescriptions) {

        GeneralName gn = accessDescription.getAccessLocation();
        if (gn.getTagNo() == GeneralName.uniformResourceIdentifier) {
            DERIA5String str = DERIA5String.getInstance(gn.getName());
            String accessLocation = str.getString();
            ocspUrlList.add(accessLocation);
        }
    }
    if (ocspUrlList.isEmpty())
        throw new CertificateVerificationException("Cant get OCSP urls from certificate");

    return ocspUrlList;
}

From source file:org.apache.synapse.transport.utils.sslcert.crl.CRLVerifier.java

License:Apache License

/**
 * Extracts all CRL distribution point URLs from the "CRL Distribution Point"
 * extension in a X.509 certificate. If CRL distribution point extension is
 * unavailable, returns an empty list.//  www  . java2 s .  c o m
 */
private List<String> getCrlDistributionPoints(X509Certificate cert) throws CertificateVerificationException {

    //Gets the DER-encoded OCTET string for the extension value for CRLDistributionPoints
    byte[] crlDPExtensionValue = cert.getExtensionValue(X509Extensions.CRLDistributionPoints.getId());
    if (crlDPExtensionValue == null)
        throw new CertificateVerificationException("Certificate doesn't have CRL " + "distribution points");
    //crlDPExtensionValue is encoded in ASN.1 format.
    ASN1InputStream asn1In = new ASN1InputStream(crlDPExtensionValue);
    // DER (Distinguished Encoding Rules) is one of ASN.1 encoding rules defined in ITU-T X.690,
    // 2002, specification. ASN.1 encoding rules can be used to encode any data object into a
    // binary file. Read the object in octets.
    CRLDistPoint distPoint;
    try {
        DEROctetString crlDEROctetString = (DEROctetString) asn1In.readObject();
        //Get Input stream in octets
        ASN1InputStream asn1InOctets = new ASN1InputStream(crlDEROctetString.getOctets());
        ASN1Primitive asn1Primitive = asn1InOctets.readObject();
        distPoint = CRLDistPoint.getInstance(asn1Primitive);
    } catch (IOException e) {
        throw new CertificateVerificationException("Cannot read certificate to get CRL urls", e);
    }

    List<String> crlUrls = new ArrayList<String>();
    //Loop through ASN1Encodable DistributionPoints
    for (DistributionPoint dp : distPoint.getDistributionPoints()) {
        //get ASN1Encodable DistributionPointName
        DistributionPointName dpn = dp.getDistributionPoint();
        if (dpn != null && dpn.getType() == DistributionPointName.FULL_NAME) {
            //Create ASN1Encodable General Names
            GeneralName[] genNames = GeneralNames.getInstance(dpn.getName()).getNames();
            // Look for a URI
            //todo: May be able to check for OCSP url specifically.
            for (GeneralName genName : genNames) {
                if (genName.getTagNo() == GeneralName.uniformResourceIdentifier) {
                    //DERIA5String contains an ascii string.
                    //A IA5String is a restricted character string type in the ASN.1 notation
                    String url = DERIA5String.getInstance(genName.getName()).getString().trim();
                    crlUrls.add(url);
                }
            }
        }
    }

    if (crlUrls.isEmpty()) {
        throw new CertificateVerificationException("Cant get CRL urls from certificate");
    }

    return crlUrls;
}

From source file:org.apache.synapse.transport.utils.sslcert.ocsp.OCSPVerifier.java

License:Apache License

/**
 * Authority Information Access (AIA) is a non-critical extension in an X509 Certificate. This contains the
 * URL of the OCSP endpoint if one is available.
 * TODO: This might contain non OCSP urls as well. Handle this.
 *
 * @param cert is the certificate//from   w w  w. j a v  a 2 s  .  c o m
 * @return a lit of URLs in AIA extension of the certificate which will hopefully contain an OCSP endpoint.
 * @throws CertificateVerificationException
 *
 */
private List<String> getAIALocations(X509Certificate cert) throws CertificateVerificationException {

    //Gets the DER-encoded OCTET string for the extension value for Authority information access Points
    byte[] aiaExtensionValue = cert.getExtensionValue(X509Extensions.AuthorityInfoAccess.getId());
    if (aiaExtensionValue == null) {
        throw new CertificateVerificationException(
                "Certificate doesn't have authority " + "information access points");
    }
    //might have to pass an ByteArrayInputStream(aiaExtensionValue)
    ASN1InputStream asn1In = new ASN1InputStream(aiaExtensionValue);
    AuthorityInformationAccess authorityInformationAccess;

    try {
        DEROctetString aiaDEROctetString = (DEROctetString) (asn1In.readObject());
        ASN1InputStream asn1InOctets = new ASN1InputStream(aiaDEROctetString.getOctets());
        ASN1Sequence aiaASN1Sequence = (ASN1Sequence) asn1InOctets.readObject();
        authorityInformationAccess = AuthorityInformationAccess.getInstance(aiaASN1Sequence);
    } catch (IOException e) {
        throw new CertificateVerificationException("Cannot read certificate to get OCSP URLs", e);
    }

    List<String> ocspUrlList = new ArrayList<String>();
    AccessDescription[] accessDescriptions = authorityInformationAccess.getAccessDescriptions();
    for (AccessDescription accessDescription : accessDescriptions) {

        GeneralName gn = accessDescription.getAccessLocation();
        if (gn.getTagNo() == GeneralName.uniformResourceIdentifier) {
            DERIA5String str = DERIA5String.getInstance(gn.getName());
            String accessLocation = str.getString();
            ocspUrlList.add(accessLocation);
        }
    }
    if (ocspUrlList.isEmpty()) {
        throw new CertificateVerificationException("Cant get OCSP urls from certificate");
    }

    return ocspUrlList;
}

From source file:org.ccnx.ccn.impl.security.crypto.util.CryptoUtil.java

License:Open Source License

/**
 * Helper method to pull SubjectAlternativeNames from a certificate. BouncyCastle has
 * one of these, but it isn't included on all platforms. We get one by default from X509Certificate
 * but it returns us a collection of ? and we can't ever know what the ? is because we might
 * get a different impl class on different platforms. So we have to roll our own.
 * //w w w  . ja va2 s . c  o m
 * We filter the general names down to ones we can handle.
 * @param certificate
 * @return
 * @throws IOException 
 * @throws CertificateEncodingException 
 */
public static ArrayList<Tuple<Integer, String>> getSubjectAlternativeNames(X509Certificate certificate)
        throws IOException, CertificateEncodingException {

    byte[] encodedExtension = certificate.getExtensionValue(X509Extensions.SubjectAlternativeName.getId());

    ArrayList<Tuple<Integer, String>> list = new ArrayList<Tuple<Integer, String>>();

    if (null == encodedExtension) {
        return list;
    }

    // content of extension is wrapped in a DEROctetString
    DEROctetString content = (DEROctetString) CryptoUtil.decode(encodedExtension);
    byte[] encapsulatedOctetString = content.getOctets();

    ASN1InputStream aIn = new ASN1InputStream(encapsulatedOctetString);
    ASN1Encodable decodedObject = (ASN1Encodable) aIn.readObject();
    ASN1Sequence sequence = (ASN1Sequence) decodedObject.getDERObject();

    Integer tag;
    GeneralName generalName;

    Enumeration<?> it = sequence.getObjects();
    while (it.hasMoreElements()) {
        generalName = GeneralName.getInstance(it.nextElement());
        tag = generalName.getTagNo();

        switch (tag) {
        case GeneralName.dNSName:
        case GeneralName.rfc822Name:
        case GeneralName.uniformResourceIdentifier:
            list.add(new Tuple<Integer, String>(tag, ((DERString) generalName.getName()).getString()));
        default:
            // ignore other types
        }
    }
    return list;
}

From source file:org.cesecore.certificates.util.cert.QCStatementExtension.java

License:Open Source License

/** Returns the 'NameRegistrationAuthorities' defined in the QCStatement extension (rfc3739).
 * //from   www  . ja v a2 s.  c  o m
 * @param cert Certificate containing the extension
 * @return String with for example 'rfc822Name=foo2bar.se, rfc822Name=bar2foo.se' etc. Supports email, dns and uri name, or null of no RAs are found.
 * @throws IOException if there is a problem parsing the certificate
 */
public static String getQcStatementAuthorities(final Certificate cert) throws IOException {
    String ret = null;
    if (cert instanceof X509Certificate) {
        final X509Certificate x509cert = (X509Certificate) cert;
        final ASN1Primitive obj = getExtensionValue(x509cert, Extension.qCStatements.getId());
        if (obj == null) {
            return null;
        }
        final ASN1Sequence seq = (ASN1Sequence) obj;
        SemanticsInformation si = null;
        // Look through all the QCStatements and see if we have a standard RFC3739 pkixQCSyntax
        for (int i = 0; i < seq.size(); i++) {
            final QCStatement qc = QCStatement.getInstance(seq.getObjectAt(i));
            final ASN1ObjectIdentifier oid = qc.getStatementId();
            if ((oid != null) && (oid.equals(RFC3739QCObjectIdentifiers.id_qcs_pkixQCSyntax_v1)
                    || oid.equals(RFC3739QCObjectIdentifiers.id_qcs_pkixQCSyntax_v2))) {
                // We MAY have a SemanticsInformation object here
                final ASN1Encodable enc = qc.getStatementInfo();
                if (enc != null) {
                    si = SemanticsInformation.getInstance(enc);
                    // We can break the loop now, we got it!
                    break;
                }
            }
        }
        if (si != null) {
            final GeneralName[] gns = si.getNameRegistrationAuthorities();
            if (gns == null) {
                return null;
            }
            final StringBuilder strBuf = new StringBuilder();
            for (int i = 0; i < gns.length; i++) {
                final GeneralName gn = gns[i];
                if (strBuf.length() != 0) {
                    // Append comma so we get nice formatting if there are more than one authority
                    strBuf.append(", ");
                }
                final String str = getGeneralNameString(gn.getTagNo(), gn.getName());
                if (str != null) {
                    strBuf.append(str);
                }
            }
            if (strBuf.length() > 0) {
                ret = strBuf.toString();
            }
        }
    }
    return ret;
}