Example usage for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream

List of usage examples for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream.

Prototype

public ASN1InputStream(byte[] input) 

Source Link

Document

Create an ASN1InputStream based on the input byte array.

Usage

From source file:eu.emi.security.authn.x509.helpers.pkipath.bc.FixedBCPKIXCertPathReviewer.java

License:Open Source License

private void checkNameConstraints() {
    X509Certificate cert = null;/*from w  w w  .  ja v a2s. c  o  m*/

    //
    // Setup
    //

    // (b)  and (c)
    PKIXNameConstraintValidator nameConstraintValidator = new PKIXNameConstraintValidator();

    //
    // process each certificate except the self issued which are not last in the path
    //
    int index;

    try {
        for (index = certs.size() - 1; index >= 0; index--) {
            //
            // certificate processing
            //    

            cert = (X509Certificate) certs.get(index);

            // b),c)

            if (!(isSelfIssued(cert) && index != 0)) {
                X500Principal principal = getSubjectPrincipal(cert);
                ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(principal.getEncoded()));
                ASN1Sequence dns;

                try {
                    dns = (ASN1Sequence) aIn.readObject();
                } catch (IOException e) {
                    ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.ncSubjectNameError",
                            new Object[] { new UntrustedInput(principal) });
                    throw new CertPathReviewerException(msg, e, certPath, index);
                }

                try {
                    nameConstraintValidator.checkPermittedDN(dns);
                } catch (PKIXNameConstraintValidatorException cpve) {
                    ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.notPermittedDN",
                            new Object[] { new UntrustedInput(principal.getName()) });
                    throw new CertPathReviewerException(msg, cpve, certPath, index);
                }

                try {
                    nameConstraintValidator.checkExcludedDN(dns);
                } catch (PKIXNameConstraintValidatorException cpve) {
                    ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.excludedDN",
                            new Object[] { new UntrustedInput(principal.getName()) });
                    throw new CertPathReviewerException(msg, cpve, certPath, index);
                }

                //FIX (missing in orig cert path reviewer)
                Vector emails = new X509Name(dns).getValues(X509Name.EmailAddress);
                for (Enumeration e = emails.elements(); e.hasMoreElements();) {
                    String email = (String) e.nextElement();
                    GeneralName emailAsGeneralName = new GeneralName(GeneralName.rfc822Name, email);
                    try {
                        nameConstraintValidator.checkPermitted(emailAsGeneralName);
                    } catch (PKIXNameConstraintValidatorException cpve) {
                        ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.notPermittedDN",
                                new Object[] { new UntrustedInput(principal.getName()) });
                        throw new CertPathReviewerException(msg, cpve, certPath, index);
                    }

                    try {
                        nameConstraintValidator.checkExcluded(emailAsGeneralName);
                    } catch (PKIXNameConstraintValidatorException cpve) {
                        ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.excludedDN",
                                new Object[] { new UntrustedInput(principal.getName()) });
                        throw new CertPathReviewerException(msg, cpve, certPath, index);
                    }
                }

                ASN1Sequence altName;
                try {
                    altName = (ASN1Sequence) getExtensionValue(cert, SUBJECT_ALTERNATIVE_NAME);
                } catch (AnnotatedException ae) {
                    ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.subjAltNameExtError");
                    throw new CertPathReviewerException(msg, ae, certPath, index);
                }

                if (altName != null) {
                    for (int j = 0; j < altName.size(); j++) {
                        GeneralName name = GeneralName.getInstance(altName.getObjectAt(j));

                        try {
                            nameConstraintValidator.checkPermitted(name);
                            nameConstraintValidator.checkExcluded(name);
                        } catch (PKIXNameConstraintValidatorException cpve) {
                            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME,
                                    "CertPathReviewer.notPermittedEmail",
                                    new Object[] { new UntrustedInput(name) });
                            throw new CertPathReviewerException(msg, cpve, certPath, index);
                        }
                    }
                }

            }

            //
            // prepare for next certificate
            //

            //
            // (g) handle the name constraints extension
            //
            ASN1Sequence ncSeq;
            try {
                ncSeq = (ASN1Sequence) getExtensionValue(cert, NAME_CONSTRAINTS);
            } catch (AnnotatedException ae) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.ncExtError");
                throw new CertPathReviewerException(msg, ae, certPath, index);
            }

            if (ncSeq != null) {
                NameConstraints nc = NameConstraints.getInstance(ncSeq);

                //
                // (g) (1) permitted subtrees
                //
                GeneralSubtree[] permitted = nc.getPermittedSubtrees();
                if (permitted != null) {
                    nameConstraintValidator.intersectPermittedSubtree(permitted);
                }

                //
                // (g) (2) excluded subtrees
                //
                GeneralSubtree[] excluded = nc.getExcludedSubtrees();
                if (excluded != null) {
                    for (int c = 0; c != excluded.length; c++) {
                        nameConstraintValidator.addExcludedSubtree(excluded[c]);
                    }
                }
            }

        } // for
    } catch (CertPathReviewerException cpre) {
        addError(cpre.getErrorMessage(), cpre.getIndex());
    }
}

From source file:eu.emi.security.authn.x509.helpers.pkipath.bc.RFC3280CertPathUtilitiesHelper.java

License:Open Source License

/**
 * Checks a certificate if it is revoked.
 * // w  w w .ja  va 2  s  . c o  m
 * @param paramsPKIX PKIX parameters.
 * @param cert Certificate to check if it is revoked.
 * @param validDate The date when the certificate revocation status
 *                should be checked.
 * @param sign The issuer certificate of the certificate
 *                <code>cert</code>.
 * @param workingPublicKey The public key of the issuer certificate
 *                <code>sign</code>.
 * @param certPathCerts The certificates of the certification path.
 * @throws AnnotatedException if the certificate is revoked or the
 *                 status cannot be checked or some error occurs.
 */
protected static void checkCRLs2(ExtPKIXParameters paramsPKIX, X509Certificate cert, Date validDate,
        X509Certificate sign, PublicKey workingPublicKey, List<?> certPathCerts)
        throws SimpleValidationErrorException {
    SimpleValidationErrorException lastException = null;
    CRLDistPoint crldp = null;
    try {
        crldp = CRLDistPoint.getInstance(CertPathValidatorUtilities.getExtensionValue(cert,
                RFC3280CertPathUtilities.CRL_DISTRIBUTION_POINTS));
    } catch (Exception e) {
        throw new SimpleValidationErrorException(ValidationErrorCode.crlDistPtExtError, e);
    }
    try {
        CertPathValidatorUtilities.addAdditionalStoresFromCRLDistributionPoint(crldp, paramsPKIX);
    } catch (AnnotatedException e) {
        throw new SimpleValidationErrorException(ValidationErrorCode.crlDistPtExtError, e);
    }
    CertStatus certStatus = new CertStatus();
    ReasonsMask reasonsMask = new ReasonsMask();

    boolean validCrlFound = false;
    // for each distribution point
    if (crldp != null) {
        DistributionPoint dps[] = null;
        try {
            dps = crldp.getDistributionPoints();
        } catch (Exception e) {
            throw new SimpleValidationErrorException(ValidationErrorCode.crlDistPtExtError, e);
        }
        if (dps != null) {
            for (int i = 0; i < dps.length && certStatus.getCertStatus() == CertStatus.UNREVOKED
                    && !reasonsMask.isAllReasons(); i++) {
                ExtendedPKIXParameters paramsPKIXClone = (ExtendedPKIXParameters) paramsPKIX.clone();
                try {
                    checkCRL(dps[i], paramsPKIXClone, cert, validDate, sign, workingPublicKey, certStatus,
                            reasonsMask, certPathCerts);
                    validCrlFound = true;
                } catch (SimpleValidationErrorException e) {
                    lastException = e;
                }
            }
        }
    }

    /*
     * If the revocation status has not been determined, repeat the
     * process above with any available CRLs not specified in a
     * distribution point but issued by the certificate issuer.
     */

    if (certStatus.getCertStatus() == CertStatus.UNREVOKED && !reasonsMask.isAllReasons()) {
        try {
            /*
             * assume a DP with both the reasons and the
             * cRLIssuer fields omitted and a distribution
             * point name of the certificate issuer.
             */
            ASN1Primitive issuer = null;
            try {
                issuer = new ASN1InputStream(
                        CertPathValidatorUtilities.getEncodedIssuerPrincipal(cert).getEncoded()).readObject();
            } catch (Exception e) {
                throw new SimpleValidationErrorException(ValidationErrorCode.crlIssuerException, e);
            }
            DistributionPoint dp = new DistributionPoint(new DistributionPointName(0,
                    new GeneralNames(new GeneralName(GeneralName.directoryName, issuer))), null, null);
            ExtendedPKIXParameters paramsPKIXClone = (ExtendedPKIXParameters) paramsPKIX.clone();
            checkCRL(dp, paramsPKIXClone, cert, validDate, sign, workingPublicKey, certStatus, reasonsMask,
                    certPathCerts);
            validCrlFound = true;
        } catch (SimpleValidationErrorException e) {
            lastException = e;
        }
    }

    if (!validCrlFound)
        throw lastException;
    if (certStatus.getCertStatus() != CertStatus.UNREVOKED) {
        throw new SimpleValidationErrorException(ValidationErrorCode.certRevoked,
                new TrustedInput(certStatus.getRevocationDate()), crlReasons[certStatus.getCertStatus()]);
    }
    if (!reasonsMask.isAllReasons() && certStatus.getCertStatus() == CertStatus.UNREVOKED) {
        certStatus.setCertStatus(CertStatus.UNDETERMINED);
    }
    if (certStatus.getCertStatus() == CertStatus.UNDETERMINED) {
        throw new SimpleValidationErrorException(ValidationErrorCode.noValidCrlFound);
    }
}

From source file:eu.europa.ec.markt.dss.applet.io.RemoteOCSPSource.java

License:Open Source License

@Override
public BasicOCSPResp getOCSPResponse(X509Certificate certificate, X509Certificate issuerCertificate)
        throws IOException {

    try {/*www .j  a  v a 2  s. c o m*/
        OCSPRequestMessage request = new OCSPRequestMessage();
        request.setCertificate(certificate.getEncoded());
        request.setIssuerCert(issuerCertificate.getEncoded());

        OCSPResponseMessage response = sendAndReceive(request);

        if (response.getOcspResponse() == null) {
            return null;
        } else {
            ASN1InputStream input = new ASN1InputStream(response.getOcspResponse());
            ASN1Sequence sequence = (ASN1Sequence) input.readObject().toASN1Object();
            return new BasicOCSPResp(new BasicOCSPResponse(sequence));
        }
    } catch (CertificateEncodingException e) {
        throw new IOException(e);
    }
}

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

License:Open Source License

/**
 * This method returns the reason of the revocation of the certificate extracted from the given CRL.
 *
 * @param crlEntry An object for a revoked certificate in a CRL (Certificate Revocation List).
 * @return/*from  w  w w . ja va2 s.co m*/
 * @throws DSSException
 */
public static String getRevocationReason(final X509CRLEntry crlEntry) throws DSSException {

    final String reasonId = Extension.reasonCode.getId();
    final byte[] extensionBytes = crlEntry.getExtensionValue(reasonId);
    ASN1InputStream asn1InputStream = null;
    try {

        asn1InputStream = new ASN1InputStream(extensionBytes);
        final ASN1Enumerated asn1Enumerated = ASN1Enumerated.getInstance(asn1InputStream.readObject());
        final CRLReason reason = CRLReason.getInstance(asn1Enumerated);
        return reason.toString();
    } catch (IllegalArgumentException e) {
        // In the test case XAdESTest003 testTRevoked() there is an error in the revocation reason.
        //LOG.warn("Error when revocation reason decoding from CRL: " + e.toString());
        final CRLReason reason = CRLReason.lookup(7); // 7 -> unknown
        return reason.toString(); // unknown
    } catch (IOException e) {
        throw new DSSException(e);
    } finally {

        DSSUtils.closeQuietly(asn1InputStream);
    }
}

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

License:Open Source License

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

    try {/*  w  w w. j  ava2 s  . c om*/

        final byte[] authInfoAccessExtensionValue = certificate
                .getExtensionValue(Extension.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 = AuthorityInformationAccess
                .getInstance(asn1InputStream2.readObject());
        asn1InputStream2.close();

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

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

                // LOG.debug("not a uniform resource identifier");
                continue;
            }
            final DERIA5String str = (DERIA5String) ((DERTaggedObject) gn.toASN1Primitive()).getObject();
            accessLocation = str.getString();
            // The HTTP protocol is preferred.
            if (Protocol.isHttpUrl(accessLocation)) {
                // LOG.debug("access location: " + accessLocation);
                break;
            }
        }
        return accessLocation;
    } catch (final IOException e) {

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

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

License:Open Source License

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

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

        return Collections.emptyList();
    }//from  w w w. j av  a  2 s .c om
    ASN1InputStream input = null;
    ASN1Sequence 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 = (ASN1Sequence) input.readObject();
    } catch (IOException e) {

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

        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:eu.europa.ec.markt.dss.DSSUtils.java

License:Open Source License

public static List<String> getQCStatementsIdList(final X509Certificate x509Certificate) {

    final List<String> extensionIdList = new ArrayList<String>();
    final byte[] qcStatement = x509Certificate.getExtensionValue(X509Extension.qCStatements.getId());
    if (qcStatement != null) {

        ASN1InputStream input = null;
        try {/* w w  w.  j  a  v a  2 s.  c  om*/

            input = new ASN1InputStream(qcStatement);
            final DEROctetString s = (DEROctetString) input.readObject();
            final byte[] content = s.getOctets();
            input.close();
            input = new ASN1InputStream(content);
            final ASN1Sequence seq = (ASN1Sequence) input.readObject();
            /* Sequence of QCStatement */
            for (int ii = 0; ii < seq.size(); ii++) {

                final QCStatement statement = QCStatement.getInstance(seq.getObjectAt(ii));
                extensionIdList.add(statement.getStatementId().getId());
            }
        } catch (IOException e) {

            throw new DSSException(e);
        } finally {

            DSSUtils.closeQuietly(input);
        }
    }
    return extensionIdList;
}

From source file:eu.europa.ec.markt.dss.validation.certificate.AIACertificateSource.java

License:Open Source License

@SuppressWarnings("deprecation")
private String getAccessLocation(X509Certificate certificate, DERObjectIdentifier accessMethod) {
    try {// w  w  w  . java  2s  .c om

        byte[] authInfoAccessExtensionValue = certificate
                .getExtensionValue(X509Extensions.AuthorityInfoAccess.getId());

        /* If the extension is not there, then return null */
        if (null == authInfoAccessExtensionValue) {
            return null;
        }

        /* Parse the extension */
        AuthorityInformationAccess authorityInformationAccess;
        DEROctetString oct = (DEROctetString) (new ASN1InputStream(
                new ByteArrayInputStream(authInfoAccessExtensionValue)).readObject());
        authorityInformationAccess = new AuthorityInformationAccess(
                (ASN1Sequence) new ASN1InputStream(oct.getOctets()).readObject());

        AccessDescription[] accessDescriptions = authorityInformationAccess.getAccessDescriptions();
        for (AccessDescription accessDescription : accessDescriptions) {
            LOG.fine("access method: " + accessDescription.getAccessMethod());
            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;
            }
            DERIA5String str = (DERIA5String) ((DERTaggedObject) gn.getDERObject()).getObject();
            String accessLocation = str.getString();
            LOG.fine("access location: " + accessLocation);
            return accessLocation;
        }
        return null;

    } catch (IOException e) {
        throw new RuntimeException("IO error: " + e.getMessage(), e);
    }
}

From source file:eu.europa.ec.markt.dss.validation.certificate.CertificateAndContext.java

License:Open Source License

/**
 * //from w  ww. ja v  a2  s  .c om
 * @param data
 * @return
 * @throws IOException
 */
private DERObject toDERObject(byte[] data) throws IOException {

    ByteArrayInputStream inStream = new ByteArrayInputStream(data);
    ASN1InputStream asnInputStream = new ASN1InputStream(inStream);
    DERObject object = asnInputStream.readObject();
    asnInputStream.close();
    return object;
}

From source file:eu.europa.ec.markt.dss.validation.crl.CRLCertificateVerifier.java

License:Open Source License

private BigInteger getCrlNumber(X509CRL crl) {
    byte[] crlNumberExtensionValue = crl.getExtensionValue(X509Extensions.CRLNumber.getId());
    if (null == crlNumberExtensionValue) {
        return null;
    }//w  w  w  .  j  av  a  2  s .c o  m
    try {
        DEROctetString octetString = (DEROctetString) (new ASN1InputStream(
                new ByteArrayInputStream(crlNumberExtensionValue)).readObject());
        byte[] octets = octetString.getOctets();
        DERInteger integer = (DERInteger) new ASN1InputStream(octets).readObject();
        BigInteger crlNumber = integer.getPositiveValue();
        return crlNumber;
    } catch (IOException e) {
        throw new RuntimeException("IO error: " + e.getMessage(), e);
    }
}