Search in sources :

Example 96 with ASN1Integer

use of org.openecard.bouncycastle.asn1.ASN1Integer in project xipki by xipki.

the class X509CaCmpResponderImpl method generateCertificates.

// method processP10cr
private List<CertResponse> generateCertificates(List<CertTemplateData> certTemplates, List<ASN1Integer> certReqIds, CmpRequestorInfo requestor, ASN1OctetString tid, boolean keyUpdate, PKIMessage request, CmpControl cmpControl, String msgId, AuditEvent event) {
    X509Ca ca = getCa();
    final int n = certTemplates.size();
    List<CertResponse> ret = new ArrayList<>(n);
    if (cmpControl.isGroupEnroll()) {
        try {
            List<X509CertificateInfo> certInfos;
            if (keyUpdate) {
                certInfos = ca.regenerateCertificates(certTemplates, requestor, RequestType.CMP, tid.getOctets(), msgId);
            } else {
                certInfos = ca.generateCertificates(certTemplates, requestor, RequestType.CMP, tid.getOctets(), msgId);
            }
            // save the request
            Long reqDbId = null;
            if (ca.getCaInfo().isSaveRequest()) {
                try {
                    byte[] encodedRequest = request.getEncoded();
                    reqDbId = ca.addRequest(encodedRequest);
                } catch (Exception ex) {
                    LOG.warn("could not save request");
                }
            }
            for (int i = 0; i < n; i++) {
                X509CertificateInfo certInfo = certInfos.get(i);
                ret.add(postProcessCertInfo(certReqIds.get(i), certInfo, tid, cmpControl));
                if (reqDbId != null) {
                    ca.addRequestCert(reqDbId, certInfo.getCert().getCertId());
                }
            }
        } catch (OperationException ex) {
            for (int i = 0; i < n; i++) {
                ret.add(postProcessException(certReqIds.get(i), ex));
            }
        }
    } else {
        Long reqDbId = null;
        boolean savingRequestFailed = false;
        for (int i = 0; i < n; i++) {
            CertTemplateData certTemplate = certTemplates.get(i);
            ASN1Integer certReqId = certReqIds.get(i);
            X509CertificateInfo certInfo;
            try {
                if (keyUpdate) {
                    certInfo = ca.regenerateCertificate(certTemplate, requestor, RequestType.CMP, tid.getOctets(), msgId);
                } else {
                    certInfo = ca.generateCertificate(certTemplate, requestor, RequestType.CMP, tid.getOctets(), msgId);
                }
                if (ca.getCaInfo().isSaveRequest()) {
                    if (reqDbId == null && !savingRequestFailed) {
                        try {
                            byte[] encodedRequest = request.getEncoded();
                            reqDbId = ca.addRequest(encodedRequest);
                        } catch (Exception ex) {
                            savingRequestFailed = true;
                            LOG.warn("could not save request");
                        }
                    }
                    if (reqDbId != null) {
                        ca.addRequestCert(reqDbId, certInfo.getCert().getCertId());
                    }
                }
                ret.add(postProcessCertInfo(certReqId, certInfo, tid, cmpControl));
            } catch (OperationException ex) {
                ret.add(postProcessException(certReqId, ex));
            }
        }
    }
    return ret;
}
Also used : CertResponse(org.bouncycastle.asn1.cmp.CertResponse) X509Ca(org.xipki.ca.server.impl.X509Ca) ArrayList(java.util.ArrayList) X509CertificateInfo(org.xipki.ca.api.publisher.x509.X509CertificateInfo) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) IOException(java.io.IOException) OperationException(org.xipki.ca.api.OperationException) CaMgmtException(org.xipki.ca.server.mgmt.api.CaMgmtException) ParseException(java.text.ParseException) CRLException(java.security.cert.CRLException) CRMFException(org.bouncycastle.cert.crmf.CRMFException) InsuffientPermissionException(org.xipki.ca.api.InsuffientPermissionException) CertTemplateData(org.xipki.ca.server.impl.CertTemplateData) OperationException(org.xipki.ca.api.OperationException)

Example 97 with ASN1Integer

use of org.openecard.bouncycastle.asn1.ASN1Integer in project xipki by xipki.

the class CmpRequestor method buildMessageWithXipkAction.

// method verifyProtection
protected PKIMessage buildMessageWithXipkAction(int action, ASN1Encodable value) throws CmpRequestorException {
    PKIHeader header = buildPkiHeader(null);
    ASN1EncodableVector vec = new ASN1EncodableVector();
    vec.add(new ASN1Integer(action));
    if (value != null) {
        vec.add(value);
    }
    InfoTypeAndValue itv = new InfoTypeAndValue(ObjectIdentifiers.id_xipki_cmp_cmpGenmsg, new DERSequence(vec));
    GenMsgContent genMsgContent = new GenMsgContent(itv);
    PKIBody body = new PKIBody(PKIBody.TYPE_GEN_MSG, genMsgContent);
    return new PKIMessage(header, body);
}
Also used : PKIHeader(org.bouncycastle.asn1.cmp.PKIHeader) ProtectedPKIMessage(org.bouncycastle.cert.cmp.ProtectedPKIMessage) PKIMessage(org.bouncycastle.asn1.cmp.PKIMessage) GeneralPKIMessage(org.bouncycastle.cert.cmp.GeneralPKIMessage) PKIBody(org.bouncycastle.asn1.cmp.PKIBody) DERSequence(org.bouncycastle.asn1.DERSequence) GenMsgContent(org.bouncycastle.asn1.cmp.GenMsgContent) InfoTypeAndValue(org.bouncycastle.asn1.cmp.InfoTypeAndValue) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) ASN1Integer(org.bouncycastle.asn1.ASN1Integer)

Example 98 with ASN1Integer

use of org.openecard.bouncycastle.asn1.ASN1Integer in project xipki by xipki.

the class X509CmpRequestor method buildRevokeCertRequest.

private PKIMessage buildRevokeCertRequest(RevokeCertRequest request) throws CmpRequestorException {
    PKIHeader header = buildPkiHeader(null);
    List<RevokeCertRequestEntry> requestEntries = request.getRequestEntries();
    List<RevDetails> revDetailsArray = new ArrayList<>(requestEntries.size());
    for (RevokeCertRequestEntry requestEntry : requestEntries) {
        CertTemplateBuilder certTempBuilder = new CertTemplateBuilder();
        certTempBuilder.setIssuer(requestEntry.getIssuer());
        certTempBuilder.setSerialNumber(new ASN1Integer(requestEntry.getSerialNumber()));
        byte[] aki = requestEntry.getAuthorityKeyIdentifier();
        if (aki != null) {
            Extensions certTempExts = getCertTempExtensions(aki);
            certTempBuilder.setExtensions(certTempExts);
        }
        Date invalidityDate = requestEntry.getInvalidityDate();
        int idx = (invalidityDate == null) ? 1 : 2;
        Extension[] extensions = new Extension[idx];
        try {
            ASN1Enumerated reason = new ASN1Enumerated(requestEntry.getReason());
            extensions[0] = new Extension(Extension.reasonCode, true, new DEROctetString(reason.getEncoded()));
            if (invalidityDate != null) {
                ASN1GeneralizedTime time = new ASN1GeneralizedTime(invalidityDate);
                extensions[1] = new Extension(Extension.invalidityDate, true, new DEROctetString(time.getEncoded()));
            }
        } catch (IOException ex) {
            throw new CmpRequestorException(ex.getMessage(), ex);
        }
        Extensions exts = new Extensions(extensions);
        RevDetails revDetails = new RevDetails(certTempBuilder.build(), exts);
        revDetailsArray.add(revDetails);
    }
    RevReqContent content = new RevReqContent(revDetailsArray.toArray(new RevDetails[0]));
    PKIBody body = new PKIBody(PKIBody.TYPE_REVOCATION_REQ, content);
    return new PKIMessage(header, body);
}
Also used : PKIHeader(org.bouncycastle.asn1.cmp.PKIHeader) PKIMessage(org.bouncycastle.asn1.cmp.PKIMessage) RevokeCertRequestEntry(org.xipki.ca.client.api.dto.RevokeCertRequestEntry) PKIBody(org.bouncycastle.asn1.cmp.PKIBody) ArrayList(java.util.ArrayList) ASN1GeneralizedTime(org.bouncycastle.asn1.ASN1GeneralizedTime) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) IOException(java.io.IOException) Extensions(org.bouncycastle.asn1.x509.Extensions) RevReqContent(org.bouncycastle.asn1.cmp.RevReqContent) Date(java.util.Date) DEROctetString(org.bouncycastle.asn1.DEROctetString) Extension(org.bouncycastle.asn1.x509.Extension) CertTemplateBuilder(org.bouncycastle.asn1.crmf.CertTemplateBuilder) ASN1Enumerated(org.bouncycastle.asn1.ASN1Enumerated) RevDetails(org.bouncycastle.asn1.cmp.RevDetails)

Example 99 with ASN1Integer

use of org.openecard.bouncycastle.asn1.ASN1Integer in project xipki by xipki.

the class X509CmpRequestor method downloadCrl.

public X509CRL downloadCrl(BigInteger crlNumber, RequestResponseDebug debug) throws CmpRequestorException, PkiErrorException {
    Integer action = null;
    PKIMessage request;
    if (crlNumber == null) {
        ASN1ObjectIdentifier type = CMPObjectIdentifiers.it_currentCRL;
        request = buildMessageWithGeneralMsgContent(type, null);
    } else {
        action = XiSecurityConstants.CMP_ACTION_GET_CRL_WITH_SN;
        request = buildMessageWithXipkAction(action, new ASN1Integer(crlNumber));
    }
    PkiResponse response = signAndSend(request, debug);
    return evaluateCrlResponse(response, action);
}
Also used : ASN1Integer(org.bouncycastle.asn1.ASN1Integer) BigInteger(java.math.BigInteger) PKIMessage(org.bouncycastle.asn1.cmp.PKIMessage) PkiResponse(org.xipki.cmp.PkiResponse) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 100 with ASN1Integer

use of org.openecard.bouncycastle.asn1.ASN1Integer in project xipki by xipki.

the class X509Ca method generateCrl0.

private X509CRL generateCrl0(boolean deltaCrl, Date thisUpdate, Date nextUpdate, AuditEvent event, String msgId) throws OperationException {
    X509CrlSignerEntryWrapper crlSigner = getCrlSigner();
    if (crlSigner == null) {
        throw new OperationException(ErrorCode.NOT_PERMITTED, "CRL generation is not allowed");
    }
    LOG.info("     START generateCrl: ca={}, deltaCRL={}, nextUpdate={}", caIdent, deltaCrl, nextUpdate);
    event.addEventData(CaAuditConstants.NAME_crlType, deltaCrl ? "DELTA_CRL" : "FULL_CRL");
    if (nextUpdate == null) {
        event.addEventData(CaAuditConstants.NAME_nextUpdate, "null");
    } else {
        event.addEventData(CaAuditConstants.NAME_nextUpdate, DateUtil.toUtcTimeyyyyMMddhhmmss(nextUpdate));
        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 successful = false;
    try {
        ConcurrentContentSigner tmpCrlSigner = crlSigner.getSigner();
        CrlControl control = crlSigner.getCrlControl();
        boolean directCrl;
        X500Name crlIssuer;
        if (tmpCrlSigner == null) {
            directCrl = true;
            crlIssuer = caInfo.getPublicCaInfo().getX500Subject();
        } else {
            directCrl = false;
            crlIssuer = X500Name.getInstance(tmpCrlSigner.getCertificate().getSubjectX500Principal().getEncoded());
        }
        X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(crlIssuer, thisUpdate);
        if (nextUpdate != null) {
            crlBuilder.setNextUpdate(nextUpdate);
        }
        final int numEntries = 100;
        Date notExpireAt;
        if (control.isIncludeExpiredCerts()) {
            notExpireAt = new Date(0);
        } else {
            // 10 minutes buffer
            notExpireAt = new Date(thisUpdate.getTime() - 600L * MS_PER_SECOND);
        }
        long startId = 1;
        // we have to cache the serial entries to sort them
        List<CertRevInfoWithSerial> allRevInfos = new LinkedList<>();
        List<CertRevInfoWithSerial> revInfos;
        do {
            if (deltaCrl) {
                revInfos = certstore.getCertsForDeltaCrl(caIdent, startId, numEntries, control.isOnlyContainsCaCerts(), control.isOnlyContainsUserCerts());
            } else {
                revInfos = certstore.getRevokedCerts(caIdent, notExpireAt, startId, numEntries, control.isOnlyContainsCaCerts(), control.isOnlyContainsUserCerts());
            }
            allRevInfos.addAll(revInfos);
            long maxId = 1;
            for (CertRevInfoWithSerial revInfo : revInfos) {
                if (revInfo.getId() > maxId) {
                    maxId = revInfo.getId();
                }
            }
            // end for
            startId = maxId + 1;
        } while (// end do
        revInfos.size() >= numEntries);
        if (revInfos != null) {
            // free the memory
            revInfos.clear();
        }
        // sort the list by SerialNumber ASC
        Collections.sort(allRevInfos);
        boolean isFirstCrlEntry = true;
        for (CertRevInfoWithSerial revInfo : allRevInfos) {
            CrlReason reason = revInfo.getReason();
            if (crlControl.isExcludeReason() && reason != CrlReason.REMOVE_FROM_CRL) {
                reason = CrlReason.UNSPECIFIED;
            }
            Date revocationTime = revInfo.getRevocationTime();
            Date invalidityTime = revInfo.getInvalidityTime();
            switch(crlControl.getInvalidityDateMode()) {
                case FORBIDDEN:
                    invalidityTime = null;
                    break;
                case OPTIONAL:
                    break;
                case REQUIRED:
                    if (invalidityTime == null) {
                        invalidityTime = revocationTime;
                    }
                    break;
                default:
                    throw new RuntimeException("unknown TripleState: " + crlControl.getInvalidityDateMode());
            }
            BigInteger serial = revInfo.getSerial();
            LOG.debug("added cert ca={} serial={} to CRL", caIdent, serial);
            if (directCrl || !isFirstCrlEntry) {
                if (invalidityTime != null) {
                    crlBuilder.addCRLEntry(serial, revocationTime, reason.getCode(), invalidityTime);
                } else {
                    crlBuilder.addCRLEntry(serial, 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);
            crlBuilder.addCRLEntry(serial, revocationTime, new Extensions(extensions.toArray(new Extension[0])));
            isFirstCrlEntry = false;
        }
        // free the memory
        allRevInfos.clear();
        BigInteger crlNumber = caInfo.nextCrlNumber();
        event.addEventData(CaAuditConstants.NAME_crlNumber, crlNumber);
        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 || onlyCaCerts || !directCrl) {
                IssuingDistributionPoint idp = new IssuingDistributionPoint(// distributionPoint,
                (DistributionPointName) null, // onlyContainsUserCerts,
                onlyUserCerts, // onlyContainsCACerts,
                onlyCaCerts, // onlySomeReasons,
                (ReasonFlags) null, // indirectCRL,
                !directCrl, // onlyContainsAttributeCerts
                false);
                crlBuilder.addExtension(Extension.issuingDistributionPoint, true, idp);
            }
            // freshestCRL
            List<String> deltaCrlUris = getCaInfo().getPublicCaInfo().getDeltaCrlUris();
            if (control.getDeltaCrlIntervals() > 0 && CollectionUtil.isNonEmpty(deltaCrlUris)) {
                CRLDistPoint cdp = CaUtil.createCrlDistributionPoints(deltaCrlUris, caInfo.getPublicCaInfo().getX500Subject(), crlIssuer);
                crlBuilder.addExtension(Extension.freshestCRL, false, cdp);
            }
        } catch (CertIOException ex) {
            LogUtil.error(LOG, ex, "crlBuilder.addExtension");
            throw new OperationException(ErrorCode.INVALID_EXTENSION, ex);
        }
        addXipkiCertset(crlBuilder, deltaCrl, control, notExpireAt, onlyCaCerts, onlyUserCerts);
        ConcurrentContentSigner concurrentSigner = (tmpCrlSigner == null) ? caInfo.getSigner(null) : tmpCrlSigner;
        ConcurrentBagEntrySigner signer0;
        try {
            signer0 = concurrentSigner.borrowSigner();
        } catch (NoIdleSignerException ex) {
            throw new OperationException(ErrorCode.SYSTEM_FAILURE, "NoIdleSignerException: " + ex.getMessage());
        }
        X509CRLHolder crlHolder;
        try {
            crlHolder = crlBuilder.build(signer0.value());
        } finally {
            concurrentSigner.requiteSigner(signer0);
        }
        try {
            X509CRL crl = X509Util.toX509Crl(crlHolder.toASN1Structure());
            caInfo.getCaEntry().setNextCrlNumber(crlNumber.longValue() + 1);
            caManager.commitNextCrlNo(caIdent, caInfo.getCaEntry().getNextCrlNumber());
            publishCrl(crl);
            successful = true;
            LOG.info("SUCCESSFUL generateCrl: ca={}, crlNumber={}, thisUpdate={}", caIdent, crlNumber, crl.getThisUpdate());
            if (!deltaCrl) {
                // clean up the CRL
                cleanupCrlsWithoutException(msgId);
            }
            return crl;
        } catch (CRLException | CertificateException ex) {
            throw new OperationException(ErrorCode.CRL_FAILURE, ex);
        }
    } finally {
        if (!successful) {
            LOG.info("    FAILED generateCrl: ca={}", caIdent);
        }
    }
}
Also used : CrlControl(org.xipki.ca.server.mgmt.api.x509.CrlControl) IssuingDistributionPoint(org.bouncycastle.asn1.x509.IssuingDistributionPoint) X509CRL(java.security.cert.X509CRL) ArrayList(java.util.ArrayList) AuthorityKeyIdentifier(org.bouncycastle.asn1.x509.AuthorityKeyIdentifier) CertificateException(java.security.cert.CertificateException) X500Name(org.bouncycastle.asn1.x500.X500Name) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) Extensions(org.bouncycastle.asn1.x509.Extensions) NoIdleSignerException(org.xipki.security.exception.NoIdleSignerException) X509v2CRLBuilder(org.bouncycastle.cert.X509v2CRLBuilder) CrlReason(org.xipki.security.CrlReason) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint) CRLException(java.security.cert.CRLException) OperationException(org.xipki.ca.api.OperationException) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) CertIOException(org.bouncycastle.cert.CertIOException) ConcurrentBagEntrySigner(org.xipki.security.ConcurrentBagEntrySigner) IssuingDistributionPoint(org.bouncycastle.asn1.x509.IssuingDistributionPoint) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint) Date(java.util.Date) LinkedList(java.util.LinkedList) Extension(org.bouncycastle.asn1.x509.Extension) ConcurrentContentSigner(org.xipki.security.ConcurrentContentSigner) X509CRLHolder(org.bouncycastle.cert.X509CRLHolder) BigInteger(java.math.BigInteger)

Aggregations

ASN1Integer (org.bouncycastle.asn1.ASN1Integer)120 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)54 DERSequence (org.bouncycastle.asn1.DERSequence)48 IOException (java.io.IOException)43 BigInteger (java.math.BigInteger)43 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)39 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)28 DEROctetString (org.bouncycastle.asn1.DEROctetString)21 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)20 ArrayList (java.util.ArrayList)18 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)18 DERUTF8String (org.bouncycastle.asn1.DERUTF8String)15 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)15 X509Certificate (java.security.cert.X509Certificate)14 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)14 Date (java.util.Date)12 DLSequence (org.bouncycastle.asn1.DLSequence)12 KeyPair (java.security.KeyPair)11 HashMap (java.util.HashMap)11 HashSet (java.util.HashSet)11