Example usage for java.security.cert X509Certificate getExtensionValue

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

Introduction

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

Prototype

public byte[] getExtensionValue(String oid);

Source Link

Document

Gets the DER-encoded OCTET string for the extension value (extnValue) identified by the passed-in oid String.

Usage

From source file:tools.pki.gbay.crypto.keys.validation.CertificateRevocationList.java

/**
 * 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.
 * @param cert /*from   w  w  w .j  a  v  a 2  s  .  com*/
 * @return List of all CRL DPs
 * @throws CertificateParsingException 
 * @throws IOException 
 */
public static List<String> getCrlDistributionPoints(X509Certificate cert)
        throws CertificateParsingException, IOException {
    byte[] crldpExt = cert.getExtensionValue(Extension.cRLDistributionPoints.getId());
    if (crldpExt == null) {
        return new ArrayList<String>();
    }
    ASN1InputStream oAsnInStream = new ASN1InputStream(new ByteArrayInputStream(crldpExt));
    ASN1Primitive derObjCrlDP = oAsnInStream.readObject();
    DEROctetString dosCrlDP = (DEROctetString) derObjCrlDP;
    byte[] crldpExtOctets = dosCrlDP.getOctets();
    ASN1InputStream oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(crldpExtOctets));
    ASN1Primitive 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 && 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();
                    log.debug("URL : " + url);
                    crlUrls.add(url);
                }
            }
        }
    }
    oAsnInStream.close();
    oAsnInStream2.close();
    return crlUrls;
}

From source file:org.apache.xml.security.keys.content.x509.XMLX509SKI.java

/**
 * Method getSKIBytesFromCert/*from   w  w w  . j  av  a 2 s  .c  o  m*/
 *
 * @param cert
 * @return ski bytes from the given certificate
 *
 * @throws XMLSecurityException
 * @see java.security.cert.X509Extension#getExtensionValue(java.lang.String)
 */
public static byte[] getSKIBytesFromCert(X509Certificate cert) throws XMLSecurityException {

    if (cert.getVersion() < 3) {
        Object exArgs[] = { Integer.valueOf(cert.getVersion()) };
        throw new XMLSecurityException("certificate.noSki.lowVersion", exArgs);
    }

    /*
     * Gets the DER-encoded OCTET string for the extension value 
     * (extnValue) identified by the passed-in oid String. The oid 
     * string is represented by a set of positive whole numbers 
     * separated by periods.
     */
    byte[] extensionValue = cert.getExtensionValue(XMLX509SKI.SKI_OID);
    if (extensionValue == null) {
        throw new XMLSecurityException("certificate.noSki.null");
    }

    /**
     * Strip away first four bytes from the extensionValue 
     * The first two bytes are the tag and length of the extensionValue
     * OCTET STRING, and the next two bytes are the tag and length of
     * the ski OCTET STRING.
     */
    byte skidValue[] = new byte[extensionValue.length - 4];

    System.arraycopy(extensionValue, 4, skidValue, 0, skidValue.length);

    if (log.isDebugEnabled()) {
        log.debug("Base64 of SKI is " + Base64.encode(skidValue));
    }

    return skidValue;
}

From source file:eu.europa.ec.markt.dss.DSSUtils.java

public static List<String> getPolicyIdentifiers(X509Certificate cert) {

    final byte[] certificatePolicies = cert.getExtensionValue(X509Extension.certificatePolicies.getId());
    if (certificatePolicies == null) {

        return Collections.emptyList();
    }/*from  w ww . java2s . c  o m*/
    ASN1InputStream input = null;
    DERSequence seq = null;
    try {

        input = new ASN1InputStream(certificatePolicies);
        final DEROctetString s = (DEROctetString) input.readObject();
        final byte[] content = s.getOctets();
        input.close();
        input = new ASN1InputStream(content);
        seq = (DERSequence) input.readObject();
    } catch (IOException e) {

        throw new DSSException("Error when computing certificate's extensions.", e);
    } finally {

        DSSUtils.closeQuietly(input);
    }
    final List<String> policyIdentifiers = new ArrayList<String>();
    for (int ii = 0; ii < seq.size(); ii++) {

        final PolicyInformation policyInfo = PolicyInformation.getInstance(seq.getObjectAt(ii));
        // System.out.println("\t----> PolicyIdentifier: " + policyInfo.getPolicyIdentifier().getId());
        policyIdentifiers.add(policyInfo.getPolicyIdentifier().getId());

    }
    return policyIdentifiers;
}

From source file:com.peterphi.std.crypto.keygen.CaHelper.java

public static PKCS10CertificationRequest generateCertificateRequest(X509Certificate cert, PrivateKey signingKey)
        throws Exception {
    ASN1EncodableVector attributes = new ASN1EncodableVector();

    Set<String> nonCriticalExtensionOIDs = cert.getNonCriticalExtensionOIDs();
    for (String nceoid : nonCriticalExtensionOIDs) {
        byte[] derBytes = cert.getExtensionValue(nceoid);
        ByteArrayInputStream bis = new ByteArrayInputStream(derBytes);
        ASN1InputStream dis = new ASN1InputStream(bis);
        try {/*from   ww w  . j a v  a  2s  . c o m*/
            DERObject derObject = dis.readObject();
            DERSet value = new DERSet(derObject);
            Attribute attr = new Attribute(new DERObjectIdentifier(nceoid), value);
            attributes.add(attr);
        } finally {
            IOUtils.closeQuietly(dis);
        }
    }
    PKCS10CertificationRequest certificationRequest = new PKCS10CertificationRequest(getSignatureAlgorithm(),
            cert.getSubjectX500Principal(), cert.getPublicKey(), new DERSet(attributes), signingKey);
    return certificationRequest;
}

From source file:eu.europa.ec.markt.dss.DSSUtils.java

/**
 * @param x509Certificate//from w  ww  .  j  a  v  a 2s  .  co  m
 * @return the SKI value of the certificate. Null if no such extension
 * @throws Exception
 */
public static byte[] getSki(X509Certificate x509Certificate) {
    try {
        final byte[] extensionValue = x509Certificate.getExtensionValue("2.5.29.14");
        if (extensionValue == null) {
            return null;
        }
        ASN1OctetString str = ASN1OctetString
                .getInstance(new ASN1InputStream(new ByteArrayInputStream(extensionValue)).readObject());
        SubjectKeyIdentifier keyId = SubjectKeyIdentifier
                .getInstance(new ASN1InputStream(new ByteArrayInputStream(str.getOctets())).readObject());
        return keyId.getKeyIdentifier();
    } catch (IOException e) {
        throw new DSSException(e);
    }
}

From source file:be.fedict.eid.tsl.Tsl2PdfExporter.java

private static List<String> getCrlDistributionPoints(final X509Certificate cert) throws IOException {
    final byte[] extValue = cert.getExtensionValue(X509Extensions.CRLDistributionPoints.getId());
    if (extValue != null) {
        final ASN1InputStream oAsnInStream = new ASN1InputStream(new ByteArrayInputStream(extValue));
        final DERObject derObj = oAsnInStream.readObject();
        final DEROctetString dos = (DEROctetString) derObj;
        final byte[] val2 = dos.getOctets();
        final ASN1InputStream oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(val2));
        final DERObject derObj2 = oAsnInStream2.readObject();
        return getDERValue(derObj2);
    } else {//from   ww w  . ja  v  a 2s .c om
        return Collections.emptyList();
    }
}

From source file:eu.europa.ec.markt.dss.DSSUtils.java

private static String getAccessLocation(final X509Certificate certificate,
        final DERObjectIdentifier accessMethod) {

    try {/*from   w ww .j a  va  2 s .  c o  m*/

        final byte[] authInfoAccessExtensionValue = certificate
                .getExtensionValue(X509Extension.authorityInfoAccess.getId());
        if (null == authInfoAccessExtensionValue) {
            return null;
        }
        /* Parse the extension */
        final ASN1InputStream asn1InputStream = new ASN1InputStream(
                new ByteArrayInputStream(authInfoAccessExtensionValue));
        final DEROctetString oct = (DEROctetString) (asn1InputStream.readObject());
        asn1InputStream.close();
        final ASN1InputStream asn1InputStream2 = new ASN1InputStream(oct.getOctets());
        final AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess(
                (ASN1Sequence) asn1InputStream2.readObject());
        asn1InputStream2.close();

        final AccessDescription[] accessDescriptions = authorityInformationAccess.getAccessDescriptions();
        for (final AccessDescription accessDescription : accessDescriptions) {

            // LOG.fine("access method: " + accessDescription.getAccessMethod());
            final boolean correctAccessMethod = accessDescription.getAccessMethod().equals(accessMethod);
            if (!correctAccessMethod) {
                continue;
            }
            GeneralName gn = accessDescription.getAccessLocation();
            if (gn.getTagNo() != GeneralName.uniformResourceIdentifier) {

                // LOG.fine("not a uniform resource identifier");
                continue;
            }
            final DERIA5String str = (DERIA5String) ((DERTaggedObject) gn.getDERObject()).getObject();
            final String accessLocation = str.getString();
            // LOG.fine("access location: " + accessLocation);
            return accessLocation;
        }
    } catch (final IOException e) {

        // we do nothing
        // LOG.("IO error: " + e.getMessage(), e);
    }
    return null;
}

From source file:info.guardianproject.onionkit.trust.StrongTrustManager.java

/**
 * Returns the JID representation of an XMPP entity contained as a
 * SubjectAltName extension in the certificate. If none was found then
 * return <tt>null</tt>.//  www  .  j  a va2 s .  c  om
 *
 * @param certificate the certificate presented by the remote entity.
 * @return the JID representation of an XMPP entity contained as a
 *         SubjectAltName extension in the certificate. If none was found
 *         then return <tt>null</tt>.
 */
static Collection<String> getSubjectAlternativeNames(X509Certificate certificate) {
    List<String> identities = new ArrayList<String>();
    try {
        byte[] extVal = certificate.getExtensionValue(X509Extensions.SubjectAlternativeName.getId());
        // Check that the certificate includes the SubjectAltName extension
        if (extVal == null) {
            return Collections.emptyList();
        }

        ASN1OctetString octs = (ASN1OctetString) ASN1Primitive.fromByteArray(extVal);

        @SuppressWarnings("rawtypes")
        Enumeration it = DERSequence.getInstance(ASN1Primitive.fromByteArray(octs.getOctets())).getObjects();

        while (it.hasMoreElements()) {
            GeneralName genName = GeneralName.getInstance(it.nextElement());
            switch (genName.getTagNo()) {
            case GeneralName.dNSName:
                identities.add(((ASN1String) genName.getName()).getString());
                break;
            }
        }
        return Collections.unmodifiableCollection(identities);

    } catch (Exception e) {
        Log.e(TAG, "getSubjectAlternativeNames()", e);
    }

    return identities;
}

From source file:be.fedict.trust.constraints.QCStatementsCertificateConstraint.java

public boolean check(X509Certificate certificate) {
    byte[] extensionValue = certificate.getExtensionValue(X509Extensions.QCStatements.getId());
    if (null == extensionValue) {
        return false;
    }//from  w  w w.j av a  2 s  .c om
    ASN1Sequence qcStatements;
    try {
        DEROctetString oct = (DEROctetString) (new ASN1InputStream(new ByteArrayInputStream(extensionValue))
                .readObject());
        qcStatements = (ASN1Sequence) new ASN1InputStream(oct.getOctets()).readObject();
    } catch (IOException e) {
        throw new RuntimeException("IO error: " + e.getMessage(), e);
    }
    Enumeration<?> qcStatementEnum = qcStatements.getObjects();
    boolean qcCompliance = false;
    while (qcStatementEnum.hasMoreElements()) {
        QCStatement qcStatement = QCStatement.getInstance(qcStatementEnum.nextElement());
        DERObjectIdentifier statementId = qcStatement.getStatementId();
        LOG.debug("statement Id: " + statementId.getId());
        if (QCStatement.id_etsi_qcs_QcCompliance.equals(statementId)) {
            qcCompliance = true;
        }
    }
    if (null != this.qcComplianceFilter) {
        if (qcCompliance != this.qcComplianceFilter) {
            return false;
        }
    }
    return true;
}

From source file:be.fedict.trust.constraints.CertificatePoliciesCertificateConstraint.java

public boolean check(X509Certificate certificate) {
    byte[] extensionValue = certificate.getExtensionValue(X509Extensions.CertificatePolicies.getId());
    if (null == extensionValue) {
        return false;
    }//  www . ja v  a2  s  .  c o  m
    ASN1Sequence certPolicies;
    try {
        DEROctetString oct = (DEROctetString) (new ASN1InputStream(new ByteArrayInputStream(extensionValue))
                .readObject());
        certPolicies = (ASN1Sequence) new ASN1InputStream(oct.getOctets()).readObject();
    } catch (IOException e) {
        throw new RuntimeException("IO error: " + e.getMessage(), e);
    }
    Enumeration<?> certPoliciesEnum = certPolicies.getObjects();
    while (certPoliciesEnum.hasMoreElements()) {
        PolicyInformation policyInfo = PolicyInformation.getInstance(certPoliciesEnum.nextElement());
        DERObjectIdentifier policyOid = policyInfo.getPolicyIdentifier();
        String policyId = policyOid.getId();
        LOG.debug("present policy OID: " + policyId);
        if (this.certificatePolicies.contains(policyId)) {
            LOG.debug("matching certificate policy OID: " + policyId);
            return true;
        }
    }
    return false;
}