Search in sources :

Example 21 with ASN1GeneralizedTime

use of com.unboundid.asn1.ASN1GeneralizedTime in project LinLong-Java by zhenwei1108.

the class ProvOcspRevocationChecker method check.

public void check(Certificate certificate) throws CertPathValidatorException {
    X509Certificate cert = (X509Certificate) certificate;
    Map<X509Certificate, byte[]> ocspResponses = parent.getOcspResponses();
    URI ocspUri = parent.getOcspResponder();
    if (ocspUri == null) {
        if (this.ocspURL != null) {
            try {
                ocspUri = new URI(this.ocspURL);
            } catch (URISyntaxException e) {
                throw new CertPathValidatorException("configuration error: " + e.getMessage(), e, parameters.getCertPath(), parameters.getIndex());
            }
        } else {
            ocspUri = getOcspResponderURI(cert);
        }
    }
    byte[] nonce = null;
    boolean preValidated = false;
    if (ocspResponses.get(cert) == null && ocspUri != null) {
        // if we're here we need to make a network access, if we haven't been given a URL explicitly block it.
        if (ocspURL == null && parent.getOcspResponder() == null && !isEnabledOCSP) {
            throw new RecoverableCertPathValidatorException("OCSP disabled by \"ocsp.enable\" setting", null, parameters.getCertPath(), parameters.getIndex());
        }
        com.github.zhenwei.core.asn1.x509.Certificate issuer = extractCert();
        // TODO: configure hash algorithm
        CertID id = createCertID(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1), issuer, new ASN1Integer(cert.getSerialNumber()));
        OCSPResponse response = OcspCache.getOcspResponse(id, parameters, ocspUri, parent.getOcspResponderCert(), parent.getOcspExtensions(), helper);
        try {
            ocspResponses.put(cert, response.getEncoded());
            preValidated = true;
        } catch (IOException e) {
            throw new CertPathValidatorException("unable to encode OCSP response", e, parameters.getCertPath(), parameters.getIndex());
        }
    } else {
        List exts = parent.getOcspExtensions();
        for (int i = 0; i != exts.size(); i++) {
            Extension ext = (Extension) exts.get(i);
            byte[] value = ext.getValue();
            if (OCSPObjectIdentifiers.id_pkix_ocsp_nonce.getId().equals(ext.getId())) {
                nonce = value;
            }
        }
    }
    if (!ocspResponses.isEmpty()) {
        OCSPResponse ocspResponse = OCSPResponse.getInstance(ocspResponses.get(cert));
        ASN1Integer serialNumber = new ASN1Integer(cert.getSerialNumber());
        if (ocspResponse != null) {
            if (OCSPResponseStatus.SUCCESSFUL == ocspResponse.getResponseStatus().getIntValue()) {
                ResponseBytes respBytes = ResponseBytes.getInstance(ocspResponse.getResponseBytes());
                if (respBytes.getResponseType().equals(OCSPObjectIdentifiers.id_pkix_ocsp_basic)) {
                    try {
                        BasicOCSPResponse basicResp = BasicOCSPResponse.getInstance(respBytes.getResponse().getOctets());
                        if (preValidated || validatedOcspResponse(basicResp, parameters, nonce, parent.getOcspResponderCert(), helper)) {
                            ResponseData responseData = ResponseData.getInstance(basicResp.getTbsResponseData());
                            ASN1Sequence s = responseData.getResponses();
                            CertID certID = null;
                            for (int i = 0; i != s.size(); i++) {
                                SingleResponse resp = SingleResponse.getInstance(s.getObjectAt(i));
                                if (serialNumber.equals(resp.getCertID().getSerialNumber())) {
                                    ASN1GeneralizedTime nextUp = resp.getNextUpdate();
                                    if (nextUp != null && parameters.getValidDate().after(nextUp.getDate())) {
                                        throw new ExtCertPathValidatorException("OCSP response expired");
                                    }
                                    if (certID == null || !certID.getHashAlgorithm().equals(resp.getCertID().getHashAlgorithm())) {
                                        com.github.zhenwei.core.asn1.x509.Certificate issuer = extractCert();
                                        certID = createCertID(resp.getCertID(), issuer, serialNumber);
                                    }
                                    if (certID.equals(resp.getCertID())) {
                                        if (resp.getCertStatus().getTagNo() == 0) {
                                            // we're good!
                                            return;
                                        }
                                        if (resp.getCertStatus().getTagNo() == 1) {
                                            RevokedInfo info = RevokedInfo.getInstance(resp.getCertStatus().getStatus());
                                            CRLReason reason = info.getRevocationReason();
                                            throw new CertPathValidatorException("certificate revoked, reason=(" + reason + "), date=" + info.getRevocationTime().getDate(), null, parameters.getCertPath(), parameters.getIndex());
                                        }
                                        throw new CertPathValidatorException("certificate revoked, details unknown", null, parameters.getCertPath(), parameters.getIndex());
                                    }
                                }
                            }
                        }
                    } catch (CertPathValidatorException e) {
                        throw e;
                    } catch (Exception e) {
                        throw new CertPathValidatorException("unable to process OCSP response", e, parameters.getCertPath(), parameters.getIndex());
                    }
                }
            } else {
                throw new CertPathValidatorException("OCSP response failed: " + ocspResponse.getResponseStatus().getValue(), null, parameters.getCertPath(), parameters.getIndex());
            }
        } else {
            // TODO: add checking for the OCSP extension (properly vetted)
            throw new RecoverableCertPathValidatorException("no OCSP response found for certificate", null, parameters.getCertPath(), parameters.getIndex());
        }
    } else {
        throw new RecoverableCertPathValidatorException("no OCSP response found for any certificate", null, parameters.getCertPath(), parameters.getIndex());
    }
}
Also used : SingleResponse(com.github.zhenwei.core.asn1.ocsp.SingleResponse) CertID(com.github.zhenwei.core.asn1.ocsp.CertID) ASN1GeneralizedTime(com.github.zhenwei.core.asn1.ASN1GeneralizedTime) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) AlgorithmIdentifier(com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier) BasicOCSPResponse(com.github.zhenwei.core.asn1.ocsp.BasicOCSPResponse) List(java.util.List) OCSPResponse(com.github.zhenwei.core.asn1.ocsp.OCSPResponse) BasicOCSPResponse(com.github.zhenwei.core.asn1.ocsp.BasicOCSPResponse) ResponseData(com.github.zhenwei.core.asn1.ocsp.ResponseData) ASN1Integer(com.github.zhenwei.core.asn1.ASN1Integer) IOException(java.io.IOException) RevokedInfo(com.github.zhenwei.core.asn1.ocsp.RevokedInfo) CRLReason(com.github.zhenwei.core.asn1.x509.CRLReason) X509Certificate(java.security.cert.X509Certificate) URISyntaxException(java.net.URISyntaxException) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(com.github.zhenwei.provider.jce.exception.ExtCertPathValidatorException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) NoSuchProviderException(java.security.NoSuchProviderException) Extension(java.security.cert.Extension) ResponseBytes(com.github.zhenwei.core.asn1.ocsp.ResponseBytes) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(com.github.zhenwei.provider.jce.exception.ExtCertPathValidatorException) ASN1Sequence(com.github.zhenwei.core.asn1.ASN1Sequence) ExtCertPathValidatorException(com.github.zhenwei.provider.jce.exception.ExtCertPathValidatorException)

Example 22 with ASN1GeneralizedTime

use of com.unboundid.asn1.ASN1GeneralizedTime in project LinLong-Java by zhenwei1108.

the class TimeStampTokenGenerator method createGeneralizedTime.

// we need to produce a correct DER encoding GeneralizedTime here as the BC ASN.1 library doesn't handle this properly yet.
private ASN1GeneralizedTime createGeneralizedTime(Date time) throws TSPException {
    String format = "yyyyMMddHHmmss.SSS";
    SimpleDateFormat dateF = (locale == null) ? new SimpleDateFormat(format) : new SimpleDateFormat(format, locale);
    dateF.setTimeZone(new SimpleTimeZone(0, "Z"));
    StringBuilder sBuild = new StringBuilder(dateF.format(time));
    int dotIndex = sBuild.indexOf(".");
    if (dotIndex < 0) {
        // came back in seconds only, just return
        sBuild.append("Z");
        return new ASN1GeneralizedTime(sBuild.toString());
    }
    // trim to resolution
    switch(resolution) {
        case R_TENTHS_OF_SECONDS:
            if (sBuild.length() > dotIndex + 2) {
                sBuild.delete(dotIndex + 2, sBuild.length());
            }
            break;
        case R_HUNDREDTHS_OF_SECONDS:
            if (sBuild.length() > dotIndex + 3) {
                sBuild.delete(dotIndex + 3, sBuild.length());
            }
            break;
        case R_MILLISECONDS:
            // do nothing
            break;
        default:
            throw new TSPException("unknown time-stamp resolution: " + resolution);
    }
    // remove trailing zeros
    while (sBuild.charAt(sBuild.length() - 1) == '0') {
        sBuild.deleteCharAt(sBuild.length() - 1);
    }
    if (sBuild.length() - 1 == dotIndex) {
        sBuild.deleteCharAt(sBuild.length() - 1);
    }
    sBuild.append("Z");
    return new ASN1GeneralizedTime(sBuild.toString());
}
Also used : SimpleTimeZone(java.util.SimpleTimeZone) ASN1GeneralizedTime(com.github.zhenwei.core.asn1.ASN1GeneralizedTime) SimpleDateFormat(java.text.SimpleDateFormat) MessageImprint(com.github.zhenwei.pkix.util.asn1.tsp.MessageImprint)

Example 23 with ASN1GeneralizedTime

use of com.unboundid.asn1.ASN1GeneralizedTime in project xipki by xipki.

the class P12ComplexCsrGenCmd method getAdditionalExtensions.

@Override
protected List<Extension> getAdditionalExtensions() throws BadInputException {
    List<Extension> extensions = new LinkedList<>();
    // extension admission (Germany standard commonpki)
    ASN1EncodableVector vec = new ASN1EncodableVector();
    DirectoryString[] dummyItems = new DirectoryString[] { new DirectoryString("dummy") };
    ProfessionInfo pi = new ProfessionInfo(null, dummyItems, null, "aaaab", null);
    Admissions admissions = new Admissions(null, null, new ProfessionInfo[] { pi });
    vec.add(admissions);
    AdmissionSyntax adSyn = new AdmissionSyntax(null, new DERSequence(vec));
    try {
        extensions.add(new Extension(ObjectIdentifiers.id_extension_admission, false, adSyn.getEncoded()));
    } catch (IOException ex) {
        throw new BadInputException(ex.getMessage(), ex);
    }
    // extension subjectDirectoryAttributes (RFC 3739)
    Vector<Attribute> attrs = new Vector<>();
    ASN1GeneralizedTime dateOfBirth = new ASN1GeneralizedTime("19800122120000Z");
    attrs.add(new Attribute(ObjectIdentifiers.DN_DATE_OF_BIRTH, new DERSet(dateOfBirth)));
    DERPrintableString gender = new DERPrintableString("M");
    attrs.add(new Attribute(ObjectIdentifiers.DN_GENDER, new DERSet(gender)));
    DERUTF8String placeOfBirth = new DERUTF8String("Berlin");
    attrs.add(new Attribute(ObjectIdentifiers.DN_PLACE_OF_BIRTH, new DERSet(placeOfBirth)));
    String[] countryOfCitizenshipList = { "DE", "FR" };
    for (String country : countryOfCitizenshipList) {
        DERPrintableString val = new DERPrintableString(country);
        attrs.add(new Attribute(ObjectIdentifiers.DN_COUNTRY_OF_CITIZENSHIP, new DERSet(val)));
    }
    String[] countryOfResidenceList = { "DE" };
    for (String country : countryOfResidenceList) {
        DERPrintableString val = new DERPrintableString(country);
        attrs.add(new Attribute(ObjectIdentifiers.DN_COUNTRY_OF_RESIDENCE, new DERSet(val)));
    }
    SubjectDirectoryAttributes subjectDirAttrs = new SubjectDirectoryAttributes(attrs);
    try {
        extensions.add(new Extension(Extension.subjectDirectoryAttributes, false, subjectDirAttrs.getEncoded()));
    } catch (IOException ex) {
        throw new BadInputException(ex.getMessage(), ex);
    }
    return extensions;
}
Also used : DERUTF8String(org.bouncycastle.asn1.DERUTF8String) Attribute(org.bouncycastle.asn1.x509.Attribute) SubjectDirectoryAttributes(org.bouncycastle.asn1.x509.SubjectDirectoryAttributes) ASN1GeneralizedTime(org.bouncycastle.asn1.ASN1GeneralizedTime) IOException(java.io.IOException) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DirectoryString(org.bouncycastle.asn1.x500.DirectoryString) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) DERSet(org.bouncycastle.asn1.DERSet) LinkedList(java.util.LinkedList) Extension(org.bouncycastle.asn1.x509.Extension) BadInputException(org.xipki.security.exception.BadInputException) DERSequence(org.bouncycastle.asn1.DERSequence) AdmissionSyntax(org.bouncycastle.asn1.isismtt.x509.AdmissionSyntax) Admissions(org.bouncycastle.asn1.isismtt.x509.Admissions) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) DirectoryString(org.bouncycastle.asn1.x500.DirectoryString) Vector(java.util.Vector) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) ProfessionInfo(org.bouncycastle.asn1.isismtt.x509.ProfessionInfo)

Example 24 with ASN1GeneralizedTime

use of com.unboundid.asn1.ASN1GeneralizedTime in project xipki by xipki.

the class X509CaCmpResponderImpl method cmpEnrollCert.

private PKIBody cmpEnrollCert(PKIMessage request, PKIHeaderBuilder respHeader, CmpControl cmpControl, PKIHeader reqHeader, PKIBody reqBody, CmpRequestorInfo requestor, ASN1OctetString tid, String msgId, AuditEvent event) throws InsuffientPermissionException {
    long confirmWaitTime = cmpControl.getConfirmWaitTime();
    if (confirmWaitTime < 0) {
        confirmWaitTime *= -1;
    }
    // second to millisecond
    confirmWaitTime *= 1000;
    PKIBody respBody;
    int type = reqBody.getType();
    switch(type) {
        case PKIBody.TYPE_CERT_REQ:
            checkPermission(requestor, PermissionConstants.ENROLL_CERT);
            respBody = processCr(request, requestor, tid, reqHeader, CertReqMessages.getInstance(reqBody.getContent()), cmpControl, msgId, event);
            break;
        case PKIBody.TYPE_KEY_UPDATE_REQ:
            checkPermission(requestor, PermissionConstants.KEY_UPDATE);
            respBody = processKur(request, requestor, tid, reqHeader, CertReqMessages.getInstance(reqBody.getContent()), cmpControl, msgId, event);
            break;
        case PKIBody.TYPE_P10_CERT_REQ:
            checkPermission(requestor, PermissionConstants.ENROLL_CERT);
            respBody = processP10cr(request, requestor, tid, reqHeader, CertificationRequest.getInstance(reqBody.getContent()), cmpControl, msgId, event);
            break;
        case PKIBody.TYPE_CROSS_CERT_REQ:
            checkPermission(requestor, PermissionConstants.ENROLL_CROSS);
            respBody = processCcp(request, requestor, tid, reqHeader, CertReqMessages.getInstance(reqBody.getContent()), cmpControl, msgId, event);
            break;
        default:
            throw new RuntimeException("should not reach here");
    }
    // switch type
    InfoTypeAndValue tv = null;
    if (!cmpControl.isConfirmCert() && CmpUtil.isImplictConfirm(reqHeader)) {
        pendingCertPool.removeCertificates(tid.getOctets());
        tv = CmpUtil.getImplictConfirmGeneralInfo();
    } else {
        Date now = new Date();
        respHeader.setMessageTime(new ASN1GeneralizedTime(now));
        tv = new InfoTypeAndValue(CMPObjectIdentifiers.it_confirmWaitTime, new ASN1GeneralizedTime(new Date(System.currentTimeMillis() + confirmWaitTime)));
    }
    respHeader.setGeneralInfo(tv);
    return respBody;
}
Also used : PKIBody(org.bouncycastle.asn1.cmp.PKIBody) InfoTypeAndValue(org.bouncycastle.asn1.cmp.InfoTypeAndValue) ASN1GeneralizedTime(org.bouncycastle.asn1.ASN1GeneralizedTime) Date(java.util.Date)

Example 25 with ASN1GeneralizedTime

use of com.unboundid.asn1.ASN1GeneralizedTime 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)

Aggregations

ASN1GeneralizedTime (org.bouncycastle.asn1.ASN1GeneralizedTime)24 ASN1GeneralizedTime (com.unboundid.asn1.ASN1GeneralizedTime)10 ASN1Sequence (com.unboundid.asn1.ASN1Sequence)10 IOException (java.io.IOException)10 Date (java.util.Date)10 ASN1BigInteger (com.unboundid.asn1.ASN1BigInteger)9 ASN1BitString (com.unboundid.asn1.ASN1BitString)9 ASN1Element (com.unboundid.asn1.ASN1Element)9 ASN1Integer (com.unboundid.asn1.ASN1Integer)9 ASN1Null (com.unboundid.asn1.ASN1Null)9 ASN1ObjectIdentifier (com.unboundid.asn1.ASN1ObjectIdentifier)9 DN (com.unboundid.ldap.sdk.DN)9 OID (com.unboundid.util.OID)9 Test (org.testng.annotations.Test)9 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)7 DEROctetString (org.bouncycastle.asn1.DEROctetString)7 ASN1GeneralizedTime (com.github.zhenwei.core.asn1.ASN1GeneralizedTime)6 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)6 DERUTF8String (org.bouncycastle.asn1.DERUTF8String)6 ASN1OctetString (com.unboundid.asn1.ASN1OctetString)5