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

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

Introduction

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

Prototype

int uniformResourceIdentifier

To view the source code for org.bouncycastle.asn1.x509 GeneralName uniformResourceIdentifier.

Click Source Link

Usage

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  .  com
        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;
        }
        }
    }
}

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

License:Open Source License

private void okPressed() {
    try {/* w w  w .  ja va  2s  . co m*/
        GeneralName newGeneralName = null;

        if (jrbDirectoryName.isSelected()) {
            X500Name directoryName = jdnDirectoryName.getDistinguishedName();

            if (directoryName == null) {
                JOptionPane.showMessageDialog(this,
                        res.getString("DGeneralNameChooser.DirectoryNameValueReq.message"), getTitle(),
                        JOptionPane.WARNING_MESSAGE);
                return;
            }

            newGeneralName = new GeneralName(GeneralName.directoryName, directoryName);
        } else if (jrbDnsName.isSelected()) {
            String dnsName = jtfDnsName.getText().trim();

            if (dnsName.length() == 0) {
                JOptionPane.showMessageDialog(this,
                        res.getString("DGeneralNameChooser.DnsNameValueReq.message"), getTitle(),
                        JOptionPane.WARNING_MESSAGE);
                return;
            }

            newGeneralName = new GeneralName(GeneralName.dNSName, new DERIA5String(dnsName));
        } else if (jrbIpAddress.isSelected()) {

            String ipAddress = jtfIpAddress.getText().trim();

            if (ipAddress.length() == 0) {
                JOptionPane.showMessageDialog(this,
                        res.getString("DGeneralNameChooser.IpAddressValueReq.message"), getTitle(),
                        JOptionPane.WARNING_MESSAGE);
                return;
            }

            if (!IPAddress.isValid(ipAddress)) {
                JOptionPane.showMessageDialog(this, res.getString("DGeneralNameChooser.NotAValidIP.message"),
                        getTitle(), JOptionPane.WARNING_MESSAGE);
                return;
            }

            newGeneralName = new GeneralName(GeneralName.iPAddress, ipAddress);
        } else if (jrbRegisteredId.isSelected()) {
            ASN1ObjectIdentifier registeredId = joiRegisteredId.getObjectId();

            if (registeredId == null) {
                JOptionPane.showMessageDialog(this,
                        res.getString("DGeneralNameChooser.RegisteredIdValueReq.message"), getTitle(),
                        JOptionPane.WARNING_MESSAGE);
                return;
            }

            newGeneralName = new GeneralName(GeneralName.registeredID, registeredId);
        } else if (jrbRfc822Name.isSelected()) {
            String rfc822Name = jtfRfc822Name.getText().trim();

            if (rfc822Name.length() == 0) {
                JOptionPane.showMessageDialog(this,
                        res.getString("DGeneralNameChooser.Rfc822NameValueReq.message"), getTitle(),
                        JOptionPane.WARNING_MESSAGE);
                return;
            }

            newGeneralName = new GeneralName(GeneralName.rfc822Name, new DERIA5String(rfc822Name));
        } else if (jrbUniformResourceIdentifier.isSelected()) {
            String uniformResourceIdentifier = jtfUniformResourceIdentifier.getText().trim();

            if (uniformResourceIdentifier.length() == 0) {
                JOptionPane.showMessageDialog(this,
                        res.getString("DGeneralNameChooser.UniformResourceIdentifierValueReq.message"),
                        getTitle(), JOptionPane.WARNING_MESSAGE);
                return;
            }

            newGeneralName = new GeneralName(GeneralName.uniformResourceIdentifier,
                    new DERIA5String(uniformResourceIdentifier));
        } else if (jrbPrincipalName.isSelected()) {
            String upnString = jtfPrincipalName.getText().trim();

            if (upnString.length() == 0) {
                JOptionPane.showMessageDialog(this,
                        res.getString("DGeneralNameChooser.PrincipalNameValueReq.message"), getTitle(),
                        JOptionPane.WARNING_MESSAGE);
                return;
            }

            ASN1EncodableVector asn1Vector = new ASN1EncodableVector();
            asn1Vector.add(new ASN1ObjectIdentifier(GeneralNameUtil.UPN_OID));
            asn1Vector.add(new DERTaggedObject(true, 0, new DERUTF8String(upnString)));

            newGeneralName = new GeneralName(GeneralName.otherName, new DERSequence(asn1Vector));
        }

        generalName = newGeneralName;
    } catch (Exception ex) {
        DError dError = new DError(this, ex);
        dError.setLocationRelativeTo(this);
        dError.setVisible(true);
        return;
    }

    closeDialog();
}

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  w  ww  . j  a va2 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:org.apache.cxf.ws.security.sts.provider.cert.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.
 *///  w ww  .  j  a  v a2 s. c  om
public static List<String> getCrlDistributionPoints(X509Certificate cert)
        throws CertificateParsingException, IOException {
    byte[] crldpExt = cert.getExtensionValue(X509Extensions.CRLDistributionPoints.getId());
    if (crldpExt == null) {
        List<String> emptyList = new ArrayList<String>();
        return emptyList;
    }
    ASN1InputStream oAsnInStream = new ASN1InputStream(new ByteArrayInputStream(crldpExt));
    DERObject derObjCrlDP = oAsnInStream.readObject();
    DEROctetString dosCrlDP = (DEROctetString) derObjCrlDP;
    byte[] crldpExtOctets = dosCrlDP.getOctets();
    ASN1InputStream oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(crldpExtOctets));
    DERObject derObj2 = oAsnInStream2.readObject();
    CRLDistPoint distPoint = CRLDistPoint.getInstance(derObj2);
    List<String> crlUrls = new ArrayList<String>();
    for (DistributionPoint dp : distPoint.getDistributionPoints()) {
        DistributionPointName dpn = dp.getDistributionPoint();
        // Look for URIs in fullName
        if (dpn != null) {
            if (dpn.getType() == DistributionPointName.FULL_NAME) {
                GeneralName[] genNames = GeneralNames.getInstance(dpn.getName()).getNames();
                // Look for an URI
                for (int j = 0; j < genNames.length; j++) {
                    if (genNames[j].getTagNo() == GeneralName.uniformResourceIdentifier) {
                        String url = DERIA5String.getInstance(genNames[j].getName()).getString();
                        crlUrls.add(url);
                    }
                }
            }
        }
    }
    return crlUrls;
}

From source file:org.apache.poi.poifs.crypt.PkiTestUtils.java

License:Apache License

static X509Certificate generateCertificate(PublicKey subjectPublicKey, String subjectDn, Date notBefore,
        Date notAfter, X509Certificate issuerCertificate, PrivateKey issuerPrivateKey, boolean caFlag,
        int pathLength, String crlUri, String ocspUri, KeyUsage keyUsage)
        throws IOException, OperatorCreationException, CertificateException {
    String signatureAlgorithm = "SHA1withRSA";
    X500Name issuerName;//  w  w  w. j a v a2 s . c o m
    if (issuerCertificate != null) {
        issuerName = new X509CertificateHolder(issuerCertificate.getEncoded()).getIssuer();
    } else {
        issuerName = new X500Name(subjectDn);
    }

    RSAPublicKey rsaPubKey = (RSAPublicKey) subjectPublicKey;
    RSAKeyParameters rsaSpec = new RSAKeyParameters(false, rsaPubKey.getModulus(),
            rsaPubKey.getPublicExponent());

    SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(rsaSpec);

    DigestCalculator digestCalc = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()
            .get(CertificateID.HASH_SHA1);

    X509v3CertificateBuilder certificateGenerator = new X509v3CertificateBuilder(issuerName,
            new BigInteger(128, new SecureRandom()), notBefore, notAfter, new X500Name(subjectDn),
            subjectPublicKeyInfo);

    X509ExtensionUtils exUtils = new X509ExtensionUtils(digestCalc);
    SubjectKeyIdentifier subKeyId = exUtils.createSubjectKeyIdentifier(subjectPublicKeyInfo);
    AuthorityKeyIdentifier autKeyId = (issuerCertificate != null)
            ? exUtils.createAuthorityKeyIdentifier(new X509CertificateHolder(issuerCertificate.getEncoded()))
            : exUtils.createAuthorityKeyIdentifier(subjectPublicKeyInfo);

    certificateGenerator.addExtension(Extension.subjectKeyIdentifier, false, subKeyId);
    certificateGenerator.addExtension(Extension.authorityKeyIdentifier, false, autKeyId);

    if (caFlag) {
        BasicConstraints bc;

        if (-1 == pathLength) {
            bc = new BasicConstraints(true);
        } else {
            bc = new BasicConstraints(pathLength);
        }
        certificateGenerator.addExtension(Extension.basicConstraints, false, bc);
    }

    if (null != crlUri) {
        int uri = GeneralName.uniformResourceIdentifier;
        DERIA5String crlUriDer = new DERIA5String(crlUri);
        GeneralName gn = new GeneralName(uri, crlUriDer);

        DERSequence gnDer = new DERSequence(gn);
        GeneralNames gns = GeneralNames.getInstance(gnDer);

        DistributionPointName dpn = new DistributionPointName(0, gns);
        DistributionPoint distp = new DistributionPoint(dpn, null, null);
        DERSequence distpDer = new DERSequence(distp);
        certificateGenerator.addExtension(Extension.cRLDistributionPoints, false, distpDer);
    }

    if (null != ocspUri) {
        int uri = GeneralName.uniformResourceIdentifier;
        GeneralName ocspName = new GeneralName(uri, ocspUri);

        AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess(
                X509ObjectIdentifiers.ocspAccessMethod, ocspName);

        certificateGenerator.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess);
    }

    if (null != keyUsage) {
        certificateGenerator.addExtension(Extension.keyUsage, true, keyUsage);
    }

    JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlgorithm);
    signerBuilder.setProvider("BC");

    X509CertificateHolder certHolder = certificateGenerator.build(signerBuilder.build(issuerPrivateKey));

    /*
     * Next certificate factory trick is needed to make sure that the
     * certificate delivered to the caller is provided by the default
     * security provider instead of BouncyCastle. If we don't do this trick
     * we might run into trouble when trying to use the CertPath validator.
     */
    //        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    //        certificate = (X509Certificate) certificateFactory
    //                .generateCertificate(new ByteArrayInputStream(certificate
    //                        .getEncoded()));
    return new JcaX509CertificateConverter().getCertificate(certHolder);
}

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.//  w  w w.jav a2s.  com
 */
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// w w w.  j  a  v a2s  .  com
 * @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./*from w ww.  ja v a2s .  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  . java2s  . 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.apache.zookeeper.server.quorum.QuorumSSLTest.java

License:Apache License

public X509Certificate buildEndEntityCert(KeyPair keyPair, X509Certificate caCert, PrivateKey caPrivateKey,
        String hostname, String ipAddress, String crlPath, Integer ocspPort) throws Exception {
    X509CertificateHolder holder = new JcaX509CertificateHolder(caCert);
    ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(caPrivateKey);

    List<GeneralName> generalNames = new ArrayList<>();
    if (hostname != null) {
        generalNames.add(new GeneralName(GeneralName.dNSName, hostname));
    }//from  w  w  w.ja v  a 2s  .c  o m

    if (ipAddress != null) {
        generalNames.add(new GeneralName(GeneralName.iPAddress, ipAddress));
    }

    SubjectPublicKeyInfo entityKeyInfo = SubjectPublicKeyInfoFactory
            .createSubjectPublicKeyInfo(PublicKeyFactory.createKey(keyPair.getPublic().getEncoded()));
    X509ExtensionUtils extensionUtils = new BcX509ExtensionUtils();
    X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(holder.getSubject(),
            new BigInteger(128, new Random()), certStartTime, certEndTime,
            new X500Name("CN=Test End Entity Certificate"), keyPair.getPublic())
                    .addExtension(Extension.authorityKeyIdentifier, false,
                            extensionUtils.createAuthorityKeyIdentifier(holder))
                    .addExtension(Extension.subjectKeyIdentifier, false,
                            extensionUtils.createSubjectKeyIdentifier(entityKeyInfo))
                    .addExtension(Extension.basicConstraints, true, new BasicConstraints(false))
                    .addExtension(Extension.keyUsage, true,
                            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));

    if (!generalNames.isEmpty()) {
        certificateBuilder.addExtension(Extension.subjectAlternativeName, true,
                new GeneralNames(generalNames.toArray(new GeneralName[] {})));
    }

    if (crlPath != null) {
        DistributionPointName distPointOne = new DistributionPointName(
                new GeneralNames(new GeneralName(GeneralName.uniformResourceIdentifier, "file://" + crlPath)));

        certificateBuilder.addExtension(Extension.cRLDistributionPoints, false,
                new CRLDistPoint(new DistributionPoint[] { new DistributionPoint(distPointOne, null, null) }));
    }

    if (ocspPort != null) {
        certificateBuilder.addExtension(Extension.authorityInfoAccess, false, new AuthorityInformationAccess(
                X509ObjectIdentifiers.ocspAccessMethod,
                new GeneralName(GeneralName.uniformResourceIdentifier, "http://" + hostname + ":" + ocspPort)));
    }

    return new JcaX509CertificateConverter().getCertificate(certificateBuilder.build(signer));
}