Example usage for org.bouncycastle.jce.provider X509CRLObject X509CRLObject

List of usage examples for org.bouncycastle.jce.provider X509CRLObject X509CRLObject

Introduction

In this page you can find the example usage for org.bouncycastle.jce.provider X509CRLObject X509CRLObject.

Prototype

public X509CRLObject(CertificateList c) throws CRLException 

Source Link

Usage

From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java

License:Open Source License

@SuppressWarnings("unchecked")
protected static String validarAssinaturaCMS(byte[] digest, String digestAlgorithm, byte[] assinatura,
        Date dtAssinatura) throws InvalidKeyException, SecurityException, CRLException, CertificateException,
        NoSuchProviderException, NoSuchAlgorithmException, SignatureException, AplicacaoException,
        ChainValidationException, IOException, Exception {

    final CMSSignedData s;
    if (digest != null) {
        Map<String, byte[]> map = new HashMap<String, byte[]>();
        map.put(digestAlgorithm, digest);
        s = new CMSSignedData(map, assinatura);
    } else {// www . j  ava  2s.c om
        s = new CMSSignedData(assinatura);
    }

    Store certs = s.getCertificates();
    SignerInformationStore signers = s.getSignerInfos();
    Collection<SignerInformation> c = signers.getSigners();
    Iterator<SignerInformation> it = c.iterator();
    X509CertificateHolder firstSignerCert = null;

    while (it.hasNext()) {
        SignerInformation signer = it.next();
        Collection<X509CertificateHolder> certCollection = certs.getMatches(signer.getSID());

        Iterator<X509CertificateHolder> certIt = certCollection.iterator();
        X509CertificateHolder cert = certIt.next();
        if (firstSignerCert == null)
            firstSignerCert = cert;

        if (!signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert)))
            throw new Exception("Assinatura invlida!");

        System.out.println("\nSigner Info: \n");
        System.out.println("Is Signature Valid? true");
        System.out.println("Digest: " + asHex(signer.getContentDigest()));
        System.out.println("Enc Alg Oid: " + signer.getEncryptionAlgOID());
        System.out.println("Digest Alg Oid: " + signer.getDigestAlgOID());
        System.out.println("Signature: " + asHex(signer.getSignature()));

    }

    //      X509Certificate[] cadeiaTotal = montarCadeiaOrdenadaECompleta((Collection<X509Certificate>) (certs.getCertificates(null)));
    X509Certificate[] cadeiaTotal = montarCadeiaOrdenadaECompleta(certs.getMatches(null));

    List<X509CRLObject> crls = new ArrayList<>();
    if (certs.getMatches(null) != null) {
        Enumeration ec = ASN1Set.getInstance(certs.getMatches(null)).getObjects();

        while (ec.hasMoreElements()) {
            crls.add(new X509CRLObject(CertificateList.getInstance(ec.nextElement())));
        }
    }

    final X509ChainValidator cadeia = new X509ChainValidator(cadeiaTotal,
            /* trustedAnchors */new HashSet(FachadaDeCertificadosAC.getTrustAnchors()),
            crls.toArray(new X509CRLObject[0]));

    cadeia.checkCRL(true);

    try {
        cadeia.validateChain(dtAssinatura);
    } catch (Exception e1) {
        if (e1.getMessage().endsWith("Validation time is in future.")) {
            String s1 = e1.getMessage() + " Current date: [" + new Date().toString() + "]. Record date: ["
                    + dtAssinatura + "]. LCRs' dates [";
            for (X509CRLObject crl : (Collection<X509CRLObject>) certs.getMatches(null)) {
                String s2 = crl.getIssuerX500Principal().getName();
                s2 = s2.split(",")[0];

                s1 += s2 + " (" + crl.getThisUpdate() + " - " + crl.getNextUpdate() + ") ";
            }
            s1 += "]";
            throw new AplicacaoException(s1, 0, e1);
        } else
            throw e1;
    }

    //      String s1 = firstSignerCert.getSubjectDN().getName();
    String s1 = firstSignerCert.getSubject().toString();
    s1 = obterNomeExibicao(s1);

    return s1;
}

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

License:Open Source License

protected static void getCertStatus(Date validDate, X509CRL crl, Object cert, CertStatus certStatus)
        throws SimpleValidationErrorException {
    // use BC X509CRLObject so that indirect CRLs are supported
    X509CRLObject bcCRL = null;/*w  w  w .j  a  v  a  2s  .  c o m*/
    try {
        bcCRL = new X509CRLObject(
                new CertificateList((ASN1Sequence) ASN1Sequence.fromByteArray(crl.getEncoded())));
    } catch (Exception e) {
        throw new SimpleValidationErrorException(ValidationErrorCode.unknownMsg, e);
    }
    // use BC X509CRLEntryObject, so that getCertificateIssuer() is
    // supported.
    X509CRLEntryObject crl_entry = (X509CRLEntryObject) bcCRL
            .getRevokedCertificate(CertPathValidatorUtilities.getSerialNumber(cert));
    if (crl_entry != null && (CertPathValidatorUtilities.getEncodedIssuerPrincipal(cert)
            .equals(crl_entry.getCertificateIssuer())
            || CertPathValidatorUtilities.getEncodedIssuerPrincipal(cert)
                    .equals(crl.getIssuerX500Principal()))) {
        ASN1Enumerated reasonCode = null;
        if (crl_entry.hasExtensions()) {
            try {
                reasonCode = ASN1Enumerated.getInstance(CertPathValidatorUtilities.getExtensionValue(crl_entry,
                        X509Extensions.ReasonCode.getId()));
            } catch (Exception e) {
                throw new SimpleValidationErrorException(ValidationErrorCode.crlReasonExtError, e);
            }
        }

        // for reason keyCompromise, caCompromise, aACompromise
        // or
        // unspecified
        if (!(validDate.getTime() < crl_entry.getRevocationDate().getTime()) || reasonCode == null
                || reasonCode.getValue().intValue() == 0 || reasonCode.getValue().intValue() == 1
                || reasonCode.getValue().intValue() == 2 || reasonCode.getValue().intValue() == 8) {

            // (i) or (j) (1)
            if (reasonCode != null) {
                certStatus.setCertStatus(reasonCode.getValue().intValue());
            }
            // (i) or (j) (2)
            else {
                certStatus.setCertStatus(CRLReason.unspecified);
            }
            certStatus.setRevocationDate(crl_entry.getRevocationDate());
        }
    }
}

From source file:eu.europa.ec.markt.dss.validation.cades.CAdESCRLSource.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//from ww  w.  j a va2 s.  c o  m
public List<X509CRL> getCRLsFromSignature() {
    List<X509CRL> list = new ArrayList<X509CRL>();

    try {
        // Add certificates contained in SignedData
        for (CertificateList cl : (Collection<CertificateList>) cmsSignedData.getCRLs().getMatches(null)) {
            X509CRLObject crl = new X509CRLObject(cl);
            list.add(crl);
        }

        // Add certificates in CAdES-XL certificate-values inside SignerInfo attribute if present
        SignerInformation si = cmsSignedData.getSignerInfos().get(signerId);
        if (si != null && si.getUnsignedAttributes() != null
                && si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_ets_revocationValues) != null) {

            RevocationValues revValues = RevocationValues.getInstance(si.getUnsignedAttributes()
                    .get(PKCSObjectIdentifiers.id_aa_ets_revocationValues).getAttrValues().getObjectAt(0));

            for (CertificateList crlObj : revValues.getCrlVals()) {
                X509CRLObject crl = new X509CRLObject(crlObj);
                list.add(crl);
            }
        }
    } catch (StoreException e) {
        throw new RuntimeException(e);
    } catch (CRLException e) {
        throw new RuntimeException(e);
    }

    return list;
}

From source file:eu.europa.ec.markt.dss.validation102853.cades.CAdESCRLSource.java

License:Open Source License

private static X509CRLObject getX509CRLObject(final CertificateList certificateList) throws DSSException {

    try {/*from  w  ww .j  av a 2 s .c  om*/
        return new X509CRLObject(certificateList);
    } catch (CRLException e) {
        throw new DSSException(e);
    }
}

From source file:org.xipki.ca.client.impl.X509CmpRequestor.java

License:Open Source License

private CRLResultType evaluateCRLResponse(final PKIResponse response, final Integer xipkiAction)
        throws CmpRequestorException, PKIErrorException {
    checkProtection(response);/*from  w w  w.  j  a v  a  2 s .c o  m*/

    PKIBody respBody = response.getPkiMessage().getBody();
    int bodyType = respBody.getType();

    if (PKIBody.TYPE_ERROR == bodyType) {
        ErrorMsgContent content = (ErrorMsgContent) respBody.getContent();
        throw new PKIErrorException(content.getPKIStatusInfo());
    } else if (PKIBody.TYPE_GEN_REP != bodyType) {
        throw new CmpRequestorException("unknown PKI body type " + bodyType + " instead the exceptected ["
                + PKIBody.TYPE_GEN_REP + ", " + PKIBody.TYPE_ERROR + "]");
    }

    ASN1ObjectIdentifier expectedType = xipkiAction == null ? CMPObjectIdentifiers.it_currentCRL
            : ObjectIdentifiers.id_xipki_cmp;

    GenRepContent genRep = (GenRepContent) respBody.getContent();

    InfoTypeAndValue[] itvs = genRep.toInfoTypeAndValueArray();
    InfoTypeAndValue itv = null;
    if (itvs != null && itvs.length > 0) {
        for (InfoTypeAndValue m : itvs) {
            if (expectedType.equals(m.getInfoType())) {
                itv = m;
                break;
            }
        }
    }
    if (itv == null) {
        throw new CmpRequestorException("the response does not contain InfoTypeAndValue " + expectedType);
    }

    ASN1Encodable certListAsn1Object;
    if (xipkiAction == null) {
        certListAsn1Object = itv.getInfoValue();
    } else {
        certListAsn1Object = extractXipkiActionContent(itv.getInfoValue(), xipkiAction);
    }

    CertificateList certList = CertificateList.getInstance(certListAsn1Object);

    X509CRL crl;
    try {
        crl = new X509CRLObject(certList);
    } catch (CRLException e) {
        throw new CmpRequestorException("returned CRL is invalid: " + e.getMessage());
    }

    CRLResultType result = new CRLResultType();
    result.setCRL(crl);
    return result;
}

From source file:org.xipki.ca.server.impl.X509CA.java

License:Open Source License

private X509CRL generateCRL(final boolean deltaCRL, final Date thisUpdate, final Date nextUpdate,
        final AuditEvent auditEvent) throws OperationException {
    X509CrlSignerEntryWrapper crlSigner = getCrlSigner();
    if (crlSigner == null) {
        throw new OperationException(ErrorCode.INSUFFICIENT_PERMISSION, "CRL generation is not allowed");
    }/* w w w .jav a 2 s. c o  m*/

    LOG.info("     START generateCRL: ca={}, deltaCRL={}, nextUpdate={}",
            new Object[] { caInfo.getName(), deltaCRL, nextUpdate });

    if (auditEvent != null) {
        auditEvent.addEventData(new AuditEventData("crlType", deltaCRL ? "DELTA_CRL" : "FULL_CRL"));
        if (nextUpdate != null) {
            String value;
            synchronized (dateFormat) {
                value = dateFormat.format(nextUpdate);
            }
            auditEvent.addEventData(new AuditEventData("nextUpdate", value));
        } else {
            auditEvent.addEventData(new AuditEventData("nextUpdate", "NULL"));
        }
    }

    if (nextUpdate != null) {
        if (nextUpdate.getTime() - thisUpdate.getTime() < 10 * 60 * MS_PER_SECOND) {
            // less than 10 minutes
            throw new OperationException(ErrorCode.CRL_FAILURE, "nextUpdate and thisUpdate are too close");
        }
    }

    CRLControl crlControl = crlSigner.getCRLControl();
    boolean successfull = false;

    try {
        ConcurrentContentSigner _crlSigner = crlSigner.getSigner();

        CRLControl control = crlSigner.getCRLControl();

        boolean directCRL = _crlSigner == null;
        X500Name crlIssuer = directCRL ? caInfo.getPublicCAInfo().getX500Subject()
                : X500Name.getInstance(_crlSigner.getCertificate().getSubjectX500Principal().getEncoded());

        X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(crlIssuer, thisUpdate);
        if (nextUpdate != null) {
            crlBuilder.setNextUpdate(nextUpdate);
        }

        BigInteger startSerial = BigInteger.ONE;
        final int numEntries = 100;

        X509CertWithDBCertId caCert = caInfo.getCertificate();
        List<CertRevInfoWithSerial> revInfos;
        boolean isFirstCRLEntry = true;

        Date notExpireAt;
        if (control.isIncludeExpiredCerts()) {
            notExpireAt = new Date(0);
        } else {
            // 10 minutes buffer
            notExpireAt = new Date(thisUpdate.getTime() - 600L * MS_PER_SECOND);
        }

        do {
            if (deltaCRL) {
                revInfos = certstore.getCertificatesForDeltaCRL(caCert, startSerial, numEntries,
                        control.isOnlyContainsCACerts(), control.isOnlyContainsUserCerts());
            } else {
                revInfos = certstore.getRevokedCertificates(caCert, notExpireAt, startSerial, numEntries,
                        control.isOnlyContainsCACerts(), control.isOnlyContainsUserCerts());
            }

            BigInteger maxSerial = BigInteger.ONE;

            for (CertRevInfoWithSerial revInfo : revInfos) {
                BigInteger serial = revInfo.getSerial();
                if (serial.compareTo(maxSerial) > 0) {
                    maxSerial = serial;
                }

                CRLReason reason = revInfo.getReason();
                Date revocationTime = revInfo.getRevocationTime();
                Date invalidityTime = revInfo.getInvalidityTime();
                if (invalidityTime != null && invalidityTime.equals(revocationTime)) {
                    invalidityTime = null;
                }

                if (directCRL || isFirstCRLEntry == false) {
                    if (invalidityTime != null) {
                        crlBuilder.addCRLEntry(revInfo.getSerial(), revocationTime, reason.getCode(),
                                invalidityTime);
                    } else {
                        crlBuilder.addCRLEntry(revInfo.getSerial(), revocationTime, reason.getCode());
                    }
                    continue;
                }

                List<Extension> extensions = new ArrayList<>(3);
                if (reason != CRLReason.UNSPECIFIED) {
                    Extension ext = createReasonExtension(reason.getCode());
                    extensions.add(ext);
                }
                if (invalidityTime != null) {
                    Extension ext = createInvalidityDateExtension(invalidityTime);
                    extensions.add(ext);
                }

                Extension ext = createCertificateIssuerExtension(caInfo.getPublicCAInfo().getX500Subject());
                extensions.add(ext);

                Extensions asn1Extensions = new Extensions(extensions.toArray(new Extension[0]));
                crlBuilder.addCRLEntry(revInfo.getSerial(), revocationTime, asn1Extensions);
                isFirstCRLEntry = false;
            } // end for

            startSerial = maxSerial.add(BigInteger.ONE);

        } while (revInfos.size() >= numEntries);
        // end do

        BigInteger crlNumber = caInfo.nextCRLNumber();
        if (auditEvent != null) {
            auditEvent.addEventData(new AuditEventData("crlNumber", crlNumber.toString()));
        }

        boolean onlyUserCerts = crlControl.isOnlyContainsUserCerts();
        boolean onlyCACerts = crlControl.isOnlyContainsCACerts();
        if (onlyUserCerts && onlyCACerts) {
            throw new RuntimeException("should not reach here, onlyUserCerts and onlyCACerts are both true");
        }

        try {
            // AuthorityKeyIdentifier
            byte[] akiValues = directCRL ? caInfo.getPublicCAInfo().getSubjectKeyIdentifer()
                    : crlSigner.getSubjectKeyIdentifier();
            AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(akiValues);
            crlBuilder.addExtension(Extension.authorityKeyIdentifier, false, aki);

            // add extension CRL Number
            crlBuilder.addExtension(Extension.cRLNumber, false, new ASN1Integer(crlNumber));

            // IssuingDistributionPoint
            if (onlyUserCerts == true || onlyCACerts == true || directCRL == false) {
                IssuingDistributionPoint idp = new IssuingDistributionPoint((DistributionPointName) null, // distributionPoint,
                        onlyUserCerts, // onlyContainsUserCerts,
                        onlyCACerts, // onlyContainsCACerts,
                        (ReasonFlags) null, // onlySomeReasons,
                        directCRL == false, // indirectCRL,
                        false // onlyContainsAttributeCerts
                );

                crlBuilder.addExtension(Extension.issuingDistributionPoint, true, idp);
            }
        } catch (CertIOException e) {
            final String message = "crlBuilder.addExtension";
            if (LOG.isErrorEnabled()) {
                LOG.error(LogUtil.buildExceptionLogFormat(message), e.getClass().getName(), e.getMessage());
            }
            LOG.debug(message, e);
            throw new OperationException(ErrorCode.INVALID_EXTENSION, e.getMessage());
        }

        startSerial = BigInteger.ONE;
        if (deltaCRL == false && control.isEmbedsCerts()) // XiPKI extension
        {
            ASN1EncodableVector vector = new ASN1EncodableVector();

            List<BigInteger> serials;

            do {
                serials = certstore.getCertSerials(caCert, notExpireAt, startSerial, numEntries, false,
                        onlyCACerts, onlyUserCerts);

                BigInteger maxSerial = BigInteger.ONE;
                for (BigInteger serial : serials) {
                    if (serial.compareTo(maxSerial) > 0) {
                        maxSerial = serial;
                    }

                    X509CertificateInfo certInfo;
                    try {
                        certInfo = certstore.getCertificateInfoForSerial(caCert, serial);
                    } catch (CertificateException e) {
                        throw new OperationException(ErrorCode.SYSTEM_FAILURE,
                                "CertificateException: " + e.getMessage());
                    }

                    Certificate cert = Certificate.getInstance(certInfo.getCert().getEncodedCert());

                    ASN1EncodableVector v = new ASN1EncodableVector();
                    v.add(cert);
                    String profileName = certInfo.getProfileName();
                    if (StringUtil.isNotBlank(profileName)) {
                        v.add(new DERUTF8String(certInfo.getProfileName()));
                    }
                    ASN1Sequence certWithInfo = new DERSequence(v);

                    vector.add(certWithInfo);
                } // end for

                startSerial = maxSerial.add(BigInteger.ONE);
            } while (serials.size() >= numEntries);
            // end fo

            try {
                crlBuilder.addExtension(ObjectIdentifiers.id_xipki_ext_crlCertset, false, new DERSet(vector));
            } catch (CertIOException e) {
                throw new OperationException(ErrorCode.INVALID_EXTENSION, "CertIOException: " + e.getMessage());
            }
        }

        ConcurrentContentSigner concurrentSigner = (_crlSigner == null) ? caInfo.getSigner(null) : _crlSigner;

        ContentSigner contentSigner;
        try {
            contentSigner = concurrentSigner.borrowContentSigner();
        } catch (NoIdleSignerException e) {
            throw new OperationException(ErrorCode.SYSTEM_FAILURE, "NoIdleSignerException: " + e.getMessage());
        }

        X509CRLHolder crlHolder;
        try {
            crlHolder = crlBuilder.build(contentSigner);
        } finally {
            concurrentSigner.returnContentSigner(contentSigner);
        }

        try {
            X509CRL crl = new X509CRLObject(crlHolder.toASN1Structure());
            publishCRL(crl);

            successfull = true;
            LOG.info("SUCCESSFUL generateCRL: ca={}, crlNumber={}, thisUpdate={}",
                    new Object[] { caInfo.getName(), crlNumber, crl.getThisUpdate() });

            if (deltaCRL) {
                return crl;
            }

            // clean up the CRL
            try {
                cleanupCRLs();
            } catch (Throwable t) {
                LOG.warn("could not cleanup CRLs.{}: {}", t.getClass().getName(), t.getMessage());
            }
            return crl;
        } catch (CRLException e) {
            throw new OperationException(ErrorCode.CRL_FAILURE, "CRLException: " + e.getMessage());
        }
    } finally {
        if (successfull == false) {
            LOG.info("    FAILED generateCRL: ca={}", caInfo.getName());
        }
    }
}