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.maritimecloud.pki.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  . j  ava  2  s .com
public static List<String> getCrlDistributionPoints(X509Certificate cert)
        throws CertificateParsingException, IOException {
    byte[] crldpExt = cert.getExtensionValue(Extension.cRLDistributionPoints.getId());
    if (crldpExt == null) {
        return new ArrayList<>();
    }
    ASN1InputStream oAsnInStream = new ASN1InputStream(crldpExt);
    DEROctetString dosCrlDP = (DEROctetString) oAsnInStream.readObject();
    byte[] crldpExtOctets = dosCrlDP.getOctets();
    ASN1InputStream oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(crldpExtOctets));
    CRLDistPoint crlDistPoint = CRLDistPoint.getInstance(oAsnInStream2.readObject());
    oAsnInStream.close();
    oAsnInStream2.close();
    List<String> crlUrls = new ArrayList<>();
    for (DistributionPoint dp : crlDistPoint.getDistributionPoints()) {
        DistributionPointName dpn = dp.getDistributionPoint();
        // Look for URIs in fullName
        if (dpn != null && dpn.getType() == DistributionPointName.FULL_NAME) {
            GeneralName[] genNames = GeneralNames.getInstance(dpn.getName()).getNames();
            // Look for an URI
            for (GeneralName genName : genNames) {
                if (genName.getTagNo() == GeneralName.uniformResourceIdentifier) {
                    String url = DERIA5String.getInstance(genName.getName()).getString();
                    crlUrls.add(url);
                }
            }
        }
    }
    return crlUrls;
}

From source file:net.ripe.rpki.commons.crypto.x509cert.X509CertificateUtil.java

License:BSD License

private static URI[] convertCrlDistributionPointToUris(CRLDistPoint crldp) {
    List<URI> result = new ArrayList<URI>();
    for (DistributionPoint dp : crldp.getDistributionPoints()) {
        GeneralNames names = (GeneralNames) dp.getDistributionPoint().getName();
        for (GeneralName name : names.getNames()) {
            DERIA5String uri = (DERIA5String) name.getName();
            result.add(URI.create(uri.getString()));
        }//w w w  . ja  v  a  2 s . co  m
    }
    return result.toArray(new URI[result.size()]);
}

From source file:net.ripe.rpki.commons.crypto.x509cert.X509ResourceCertificateParser.java

License:BSD License

private void testCrlDistributionPointsToUrisConversion(CRLDistPoint crldp) {
    for (DistributionPoint dp : crldp.getDistributionPoints()) {
        result.rejectIfNotNull(dp.getCRLIssuer(), CRLDP_ISSUER_OMITTED);
        result.rejectIfNotNull(dp.getReasons(), CRLDP_REASONS_OMITTED);
        if (!result.rejectIfNull(dp.getDistributionPoint(), CRLDP_PRESENT)) {
            return;
        }//from w  w  w. java  2 s.c  o m
        if (!result.rejectIfFalse(dp.getDistributionPoint().getType() == DistributionPointName.FULL_NAME,
                CRLDP_TYPE_FULL_NAME)) {
            return;
        }

        GeneralNames names = (GeneralNames) dp.getDistributionPoint().getName();
        for (GeneralName name : names.getNames()) {
            if (!result.rejectIfFalse(name.getTagNo() == GeneralName.uniformResourceIdentifier,
                    CRLDP_NAME_IS_A_URI)) {
                return;
            }
            DERIA5String uri = (DERIA5String) name.getName();
            try {
                URI.create(uri.getString());
            } catch (IllegalArgumentException e) {
                result.error(CRLDP_URI_SYNTAX);
                return;
            }
        }
    }
}

From source file:net.sf.dsig.verify.OCSPHelper.java

License:Apache License

/**
 * Retrieve the OCSP URI distribution point from an X.509 certificate, using
 * the 1.3.6.1.5.5.7.1.1 extension value
 * /*from   w ww .ja v a  2  s .  c  o  m*/
 * @param certificate the {@link X509Certificate} object
 * @return a String containing the URI of the OCSP authority info access,
 * or null if none can be found
 */
public static String getOCSPAccessLocationUri(X509Certificate certificate) {
    try {
        byte[] derAiaBytes = certificate.getExtensionValue(OID_AUTHORITYINFOACCESS);
        if (derAiaBytes == null) {
            return null;
        }

        ASN1InputStream ais = new ASN1InputStream(derAiaBytes);
        DEROctetString dos = (DEROctetString) ais.readObject();
        ais.close();

        ais = new ASN1InputStream(dos.getOctets());
        DERSequence seq = (DERSequence) ais.readObject();
        ais.close();

        AuthorityInformationAccess aia = AuthorityInformationAccess.getInstance(seq);

        for (int i = 0; i < aia.getAccessDescriptions().length; i++) {
            AccessDescription ad = aia.getAccessDescriptions()[i];
            if (!ad.getAccessMethod().equals(AccessDescription.id_ad_ocsp)) {
                continue;
            }

            GeneralName gn = ad.getAccessLocation();
            if (gn.getTagNo() == GeneralName.uniformResourceIdentifier) {
                return ((DERString) gn.getName()).getString();
            }
        }
    } catch (IOException e) {
        logger.warn("ASN.1 decoding failed; will fall back to default OCSP AccessLocation, if set");
    }

    return null;
}

From source file:net.sf.dsig.verify.X509CRLHelper.java

License:Apache License

/**
 * Retrieve the CRL URI distribution point from an X.509 certificate, using
 * the 2.5.29.31 extension value/*from   w w  w . ja v  a  2  s  .  co  m*/
 * 
 * @param certificate an {@link X509Certificate} object
 * @return a String containing the URI of the CRL distribution point, or
 * null if none can be found
 */
public static String getCRLDistributionPointUri(X509Certificate certificate) {
    byte[] derCdpBytes = certificate.getExtensionValue(OID_CRLDISTRIBUTIONPOINTS);

    if (derCdpBytes == null) {
        return null;
    }

    try {
        ASN1InputStream ais = new ASN1InputStream(derCdpBytes);
        DEROctetString dos = (DEROctetString) ais.readObject();
        ais.close();

        ais = new ASN1InputStream(dos.getOctets());
        DERSequence seq = (DERSequence) ais.readObject();
        ais.close();

        CRLDistPoint cdp = new CRLDistPoint(seq);

        for (int i = 0; i < cdp.getDistributionPoints().length; i++) {
            DistributionPoint dp = cdp.getDistributionPoints()[i];
            DistributionPointName dpn = dp.getDistributionPoint();
            GeneralNames gns = (GeneralNames) dpn.getName();
            for (int j = 0; j < gns.getNames().length; j++) {
                GeneralName gn = gns.getNames()[j];
                if (gn.getTagNo() == GeneralName.uniformResourceIdentifier) {
                    return ((DERString) gn.getName()).getString();
                }
            }
        }
    } catch (IOException e) {
        logger.warn("ASN.1 decoding failed; will fall back to default CRL DistributionPoint, if set");
    }

    return null;
}

From source file:net.sf.jsignpdf.crl.CRLInfo.java

License:Mozilla Public License

/**
 * Returns (initialized, but maybe empty) set of URLs of CRLs for given
 * certificate.//from   ww  w.  j  a  v a 2  s. c  om
 * 
 * @param aCert
 *          X509 certificate.
 * @return
 */
private Set<String> getCrlUrls(final X509Certificate aCert) {
    final Set<String> tmpResult = new HashSet<String>();
    LOGGER.info(RES.get("console.crlinfo.retrieveCrlUrl", aCert.getSubjectX500Principal().getName()));
    final byte[] crlDPExtension = aCert.getExtensionValue(X509Extension.cRLDistributionPoints.getId());
    if (crlDPExtension != null) {
        CRLDistPoint crlDistPoints = null;
        try {
            crlDistPoints = CRLDistPoint.getInstance(X509ExtensionUtil.fromExtensionValue(crlDPExtension));
        } catch (IOException e) {
            LOGGER.warn("", e);
        }
        if (crlDistPoints != null) {
            final DistributionPoint[] distPoints = crlDistPoints.getDistributionPoints();
            distPoint: for (DistributionPoint dp : distPoints) {
                final DistributionPointName dpName = dp.getDistributionPoint();
                final GeneralNames generalNames = (GeneralNames) dpName.getName();
                if (generalNames != null) {
                    final GeneralName[] generalNameArr = generalNames.getNames();
                    if (generalNameArr != null) {
                        for (final GeneralName generalName : generalNameArr) {
                            if (generalName.getTagNo() == GeneralName.uniformResourceIdentifier) {
                                final DERString derString = (DERString) generalName.getName();
                                final String uri = derString.getString();
                                if (uri != null && uri.startsWith("http")) {
                                    // ||uri.startsWith("ftp")
                                    LOGGER.info(RES.get("console.crlinfo.foundCrlUri", uri));
                                    tmpResult.add(uri);
                                    continue distPoint;
                                }
                            }
                        }
                    }
                    LOGGER.info(RES.get("console.crlinfo.noUrlInDistPoint"));
                }
            }
        }
    } else {
        LOGGER.info(RES.get("console.crlinfo.distPointNotSupported"));
    }
    return tmpResult;
}

From source file:net.sf.keystore_explorer.crypto.x509.GeneralNameUtil.java

License:Open Source License

/**
 * Get string representation for General names that cannot cause a
 * IOException to be thrown. Unsupported are ediPartyName, otherName and
 * x400Address. Returns a blank string for these.
 *
 * @param generalName//w  ww.j  av a 2  s .c om
 *            General name
 * @param addLinkForURI
 *            If true, convert URI to a clickable link
 * @return String representation of general name
 */
public static String safeToString(GeneralName generalName, boolean addLinkForURI) {

    if (generalName == null) {
        return "";
    }

    switch (generalName.getTagNo()) {
    case GeneralName.directoryName: {
        X500Name directoryName = (X500Name) generalName.getName();

        return MessageFormat.format(res.getString("GeneralNameUtil.DirectoryGeneralName"),
                directoryName.toString());
    }
    case GeneralName.dNSName: {
        DERIA5String dnsName = (DERIA5String) generalName.getName();

        return MessageFormat.format(res.getString("GeneralNameUtil.DnsGeneralName"), dnsName.getString());
    }
    case GeneralName.iPAddress: {
        byte[] ipAddressBytes = ((ASN1OctetString) generalName.getName()).getOctets();

        String ipAddressString = "";
        try {
            ipAddressString = InetAddress.getByAddress(ipAddressBytes).getHostAddress();
        } catch (UnknownHostException e) {
            // ignore -> results in empty IP address string
        }

        return MessageFormat.format(res.getString("GeneralNameUtil.IpAddressGeneralName"), ipAddressString);
    }
    case GeneralName.registeredID: {
        ASN1ObjectIdentifier registeredId = (ASN1ObjectIdentifier) generalName.getName();

        return MessageFormat.format(res.getString("GeneralNameUtil.RegisteredIdGeneralName"),
                ObjectIdUtil.toString(registeredId));
    }
    case GeneralName.rfc822Name: {
        DERIA5String rfc822Name = (DERIA5String) generalName.getName();

        return MessageFormat.format(res.getString("GeneralNameUtil.Rfc822GeneralName"), rfc822Name.getString());
    }
    case GeneralName.uniformResourceIdentifier: {
        DERIA5String uri = (DERIA5String) generalName.getName();

        String link = addLinkForURI
                ? "<html><a href=\"" + uri.getString() + "\">" + uri.getString() + "</a></html>"
                : uri.getString();

        return MessageFormat.format(res.getString("GeneralNameUtil.UriGeneralName"), link);
    }
    case GeneralName.otherName: {
        // we currently only support UPN in otherName
        String upn = parseUPN(generalName);
        return MessageFormat.format(res.getString("GeneralNameUtil.OtherGeneralName"), "UPN", upn);
    }
    default: {
        return "";
    }
    }
}

From source file:net.sf.keystore_explorer.crypto.x509.GeneralNameUtil.java

License:Open Source License

/**
 * Parse UPN/otherName/*from   ww  w .ja  v  a 2  s.c om*/
 *
 * @param generalName otherName object
 * @return UPN as string
 */
public static String parseUPN(GeneralName generalName) {
    // OtherName ::= SEQUENCE {
    //    type-id OBJECT IDENTIFIER,
    //    value [0] EXPLICIT ANY DEFINED BY type-id }

    ASN1Sequence otherName = (ASN1Sequence) generalName.getName();
    ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) otherName.getObjectAt(0);

    if (UPN_OID.equals(oid.getId())) {
        DERTaggedObject derTaggedObject = (DERTaggedObject) otherName.getObjectAt(1);
        DERUTF8String upn = DERUTF8String.getInstance(derTaggedObject.getObject());
        return MessageFormat.format(res.getString("GeneralNameUtil.OtherGeneralName"), "UPN", upn.getString());
    }

    // fallback to generic handling
    ASN1Encodable value = otherName.getObjectAt(1);
    try {
        return MessageFormat.format(res.getString("GeneralNameUtil.OtherGeneralName"),
                ObjectIdUtil.toString(oid),
                HexUtil.getHexString(value.toASN1Primitive().getEncoded(ASN1Encoding.DER)));
    } catch (IOException e) {
        return MessageFormat.format(res.getString("GeneralNameUtil.OtherGeneralName"),
                ObjectIdUtil.toString(oid), "");
    }
}

From source file:net.sf.keystore_explorer.crypto.x509.GeneralNameUtil.java

License:Open Source License

/**
 * Get string representation for all General Names.
 *
 * @param generalName//w  w w.j a  va  2s  .  c  om
 *            General name
 * @return String representation of general name
 * @throws IOException
 *             If general name is invalid
 */
public static String toString(GeneralName generalName) throws IOException {

    if (generalName == null) {
        return "";
    }

    switch (generalName.getTagNo()) {
    case GeneralName.ediPartyName: {

        /* EDIPartyName ::= SEQUENCE {
         *      nameAssigner            [0]     DirectoryString OPTIONAL,
         *      partyName               [1]     DirectoryString }
         */
        ASN1Sequence ediPartyName = (ASN1Sequence) generalName.getName();

        DirectoryString nameAssigner = DirectoryString.getInstance(ediPartyName.getObjectAt(0));
        DirectoryString partyName = DirectoryString.getInstance(ediPartyName.getObjectAt(1));

        String nameAssignerStr = null;
        if (nameAssigner != null) { // Optional
            nameAssignerStr = nameAssigner.getString();
        }

        String partyNameStr = partyName.getString();
        if (nameAssignerStr != null) {
            return MessageFormat.format(res.getString("GeneralNameUtil.EdiPartyGeneralName"), nameAssignerStr,
                    partyNameStr);
        } else {
            return MessageFormat.format(res.getString("GeneralNameUtil.EdiPartyGeneralNameNoAssigner"),
                    partyNameStr);
        }
    }
    case GeneralName.otherName: {

        return parseUPN(generalName);
    }
    case GeneralName.x400Address: {
        /*
         * No support for this at the moment - just get a hex dump
         * The Oracle CertificateFactory blows up if a certificate extension contains this anyway
         */
        ASN1Encodable x400Address = generalName.getName();

        return MessageFormat.format(res.getString("GeneralNameUtil.X400AddressGeneralName"),
                HexUtil.getHexString(x400Address.toASN1Primitive().getEncoded(ASN1Encoding.DER)));
    }
    default: {
        return safeToString(generalName, true);
    }
    }
}

From source file:net.sf.keystore_explorer.gui.crypto.generalname.DGeneralNameChooser.java

License:Open Source License

private void populate(GeneralName generalName) {
    if (generalName == null) {
        jrbDirectoryName.setSelected(true);
    } else {//from  w  ww. j av a 2s . co  m
        switch (generalName.getTagNo()) {
        case GeneralName.directoryName: {
            jrbDirectoryName.setSelected(true);
            jdnDirectoryName.setDistinguishedName((X500Name) generalName.getName());
            break;
        }
        case GeneralName.dNSName: {
            jrbDnsName.setSelected(true);
            jtfDnsName.setText(((DERIA5String) generalName.getName()).getString());
            break;
        }
        case GeneralName.iPAddress: {
            jrbIpAddress.setSelected(true);
            byte[] ipAddressBytes = ((ASN1OctetString) generalName.getName()).getOctets();
            try {
                jtfIpAddress.setText(InetAddress.getByAddress(ipAddressBytes).getHostAddress());
            } catch (UnknownHostException e) {
                // cannot happen here because user input was checked for validity
            }
            break;
        }
        case GeneralName.registeredID: {
            jrbRegisteredId.setSelected(true);
            joiRegisteredId.setObjectId((ASN1ObjectIdentifier) generalName.getName());
            break;
        }
        case GeneralName.rfc822Name: {
            jrbRfc822Name.setSelected(true);
            jtfRfc822Name.setText(((DERIA5String) generalName.getName()).getString());
            break;
        }
        case GeneralName.uniformResourceIdentifier: {
            jrbUniformResourceIdentifier.setSelected(true);
            jtfUniformResourceIdentifier.setText(((DERIA5String) generalName.getName()).getString());
            break;
        }
        case GeneralName.otherName: {
            jrbPrincipalName.setSelected(true);
            // we currently only support UPN in otherName
            jtfPrincipalName.setText(GeneralNameUtil.parseUPN(generalName));
            break;
        }
        }
    }
}