Example usage for org.bouncycastle.asn1 ASN1StreamParser ASN1StreamParser

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

Introduction

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

Prototype

public ASN1StreamParser(byte[] encoding) 

Source Link

Usage

From source file:org.xipki.ca.certprofile.XmlX509CertprofileUtil.java

License:Open Source License

public static Map<ASN1ObjectIdentifier, ExtensionValue> buildConstantExtesions(
        final ExtensionsType extensionsType) throws CertprofileException {
    if (extensionsType == null) {
        return null;
    }/*  w w  w.j a v  a2  s. c  om*/

    Map<ASN1ObjectIdentifier, ExtensionValue> map = new HashMap<>();

    for (ExtensionType m : extensionsType.getExtension()) {
        if (m.getValue() == null || m.getValue().getAny() instanceof ConstantExtValue == false) {
            continue;
        }

        ConstantExtValue extConf = (ConstantExtValue) m.getValue().getAny();
        byte[] encodedValue = extConf.getValue();
        ASN1StreamParser parser = new ASN1StreamParser(encodedValue);
        ASN1Encodable value;
        try {
            value = parser.readObject();
        } catch (IOException e) {
            throw new CertprofileException("could not parse the constant extension value", e);
        }
        ExtensionValue extension = new ExtensionValue(m.isCritical(), value);
        map.put(new ASN1ObjectIdentifier(m.getType().getValue()), extension);
    }

    if (CollectionUtil.isEmpty(map)) {
        return null;
    }

    return Collections.unmodifiableMap(map);
}

From source file:org.xipki.ca.qa.impl.X509CertprofileQAImpl.java

License:Open Source License

public static Map<ASN1ObjectIdentifier, QaExtensionValue> buildConstantExtesions(
        final ExtensionsType extensionsType) throws CertprofileException {
    if (extensionsType == null) {
        return null;
    }/*from ww  w .  j  a  va 2 s  . c  om*/

    Map<ASN1ObjectIdentifier, QaExtensionValue> map = new HashMap<>();

    for (ExtensionType m : extensionsType.getExtension()) {
        if (m.getValue() == null || m.getValue().getAny() instanceof ConstantExtValue == false) {
            continue;
        }

        ConstantExtValue extConf = (ConstantExtValue) m.getValue().getAny();
        byte[] encodedValue = extConf.getValue();
        ASN1StreamParser parser = new ASN1StreamParser(encodedValue);
        try {
            parser.readObject();
        } catch (IOException e) {
            throw new CertprofileException("could not parse the constant extension value", e);
        }
        QaExtensionValue extension = new QaExtensionValue(m.isCritical(), encodedValue);
        map.put(new ASN1ObjectIdentifier(m.getType().getValue()), extension);
    }

    if (CollectionUtil.isEmpty(map)) {
        return null;
    }

    return Collections.unmodifiableMap(map);
}

From source file:org.xipki.ocsp.server.impl.Rfc2560Servlet.java

License:Open Source License

private void processRequest(final HttpServletRequest request, final HttpServletResponse response,
        final ResponderAndRelativeUri r, final boolean getMethod) throws ServletException, IOException {
    Responder responder = r.getResponder();
    AuditEvent auditEvent = null;//from w  ww  . j  ava2 s  . c o  m

    AuditLevel auditLevel = AuditLevel.INFO;
    AuditStatus auditStatus = AuditStatus.SUCCESSFUL;
    String auditMessage = null;

    long start = 0;

    AuditLoggingService auditLoggingService = auditServiceRegister == null ? null
            : auditServiceRegister.getAuditLoggingService();

    if (auditLoggingService != null && responder.getAuditOption() != null) {
        start = System.currentTimeMillis();
        auditEvent = new AuditEvent(new Date());
        auditEvent.setApplicationName("OCSP");
        auditEvent.setName("PERF");
    }

    try {
        if (server == null) {
            String message = "responder in servlet not configured";
            LOG.error(message);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.setContentLength(0);

            auditLevel = AuditLevel.ERROR;
            auditStatus = AuditStatus.FAILED;
            auditMessage = message;
            return;
        }

        InputStream requestStream;
        if (getMethod) {
            String relativeUri = r.getRelativeUri();

            // RFC2560 A.1.1 specifies that request longer than 255 bytes SHOULD be sent by POST,
            // we support GET for longer requests anyway.
            if (relativeUri.length() > responder.getRequestOption().getMaxRequestSize()) {
                response.setContentLength(0);
                response.setStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);

                auditStatus = AuditStatus.FAILED;
                auditMessage = "request too large";
                return;
            }

            requestStream = new ByteArrayInputStream(Base64.decode(relativeUri));
        } else {
            // accept only "application/ocsp-request" as content type
            if (CT_REQUEST.equalsIgnoreCase(request.getContentType()) == false) {
                response.setContentLength(0);
                response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);

                auditStatus = AuditStatus.FAILED;
                auditMessage = "unsupporte media type " + request.getContentType();
                return;
            }

            // request too long
            if (request.getContentLength() > responder.getRequestOption().getMaxRequestSize()) {
                response.setContentLength(0);
                response.setStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);

                auditStatus = AuditStatus.FAILED;
                auditMessage = "request too large";
                return;
            } // if(CT_REQUEST)

            requestStream = request.getInputStream();
        } // end if(getMethod)

        OCSPRequest ocspRequest;
        try {
            ASN1StreamParser parser = new ASN1StreamParser(requestStream);
            ocspRequest = OCSPRequest.getInstance(parser.readObject());
        } catch (Exception e) {
            response.setContentLength(0);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);

            auditStatus = AuditStatus.FAILED;
            auditMessage = "bad request";

            final String message = "could not parse the request (OCSPRequest)";
            if (LOG.isErrorEnabled()) {
                LOG.error(LogUtil.buildExceptionLogFormat(message), e.getClass().getName(), e.getMessage());
            }
            LOG.debug(message, e);

            return;
        }

        OCSPReq ocspReq = new OCSPReq(ocspRequest);

        response.setContentType(Rfc2560Servlet.CT_RESPONSE);

        OcspRespWithCacheInfo ocspRespWithCacheInfo = server.answer(responder, ocspReq, auditEvent, getMethod);
        if (ocspRespWithCacheInfo == null) {
            auditMessage = "processRequest returned null, this should not happen";
            LOG.error(auditMessage);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.setContentLength(0);

            auditLevel = AuditLevel.ERROR;
            auditStatus = AuditStatus.FAILED;
        } else {
            OCSPResp resp = ocspRespWithCacheInfo.getResponse();
            byte[] encodedOcspResp = resp.getEncoded();
            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentLength(encodedOcspResp.length);

            ResponseCacheInfo cacheInfo = ocspRespWithCacheInfo.getCacheInfo();
            if (getMethod && cacheInfo != null) {
                long now = System.currentTimeMillis();
                // RFC 5019 6.2: Date: The date and time at which the OCSP server generated the HTTP response.
                response.setDateHeader("Date", now);
                // RFC 5019 6.2: Last-Modified: date and time at which the OCSP responder last modified the response.
                response.setDateHeader("Last-Modified", cacheInfo.getThisUpdate());
                // RFC 5019 6.2: Expires: This date and time will be the same as the nextUpdate time-stamp in the OCSP
                // response itself.
                // This is overridden by max-age on HTTP/1.1 compatible components
                if (cacheInfo.getNextUpdate() != null) {
                    response.setDateHeader("Expires", cacheInfo.getNextUpdate());
                }
                // RFC 5019 6.2: This profile RECOMMENDS that the ETag value be the ASCII HEX representation of the
                // SHA1 hash of the OCSPResponse structure.
                response.setHeader("ETag", "\"" + SecurityUtil.sha1sum(encodedOcspResp).toLowerCase() + "\"");

                // Max age must be in seconds in the cache-control header
                long maxAge;
                if (responder.getResponseOption().getCacheMaxAge() != null) {
                    maxAge = responder.getResponseOption().getCacheMaxAge().longValue();
                } else {
                    maxAge = OcspServer.defaultCacheMaxAge;
                }

                if (cacheInfo.getNextUpdate() != null) {
                    maxAge = Math.min(maxAge, (cacheInfo.getNextUpdate() - cacheInfo.getThisUpdate()) / 1000);
                }

                response.setHeader("Cache-Control",
                        "max-age=" + maxAge + ",public,no-transform,must-revalidate");
            } // end if(getMethod && cacheInfo != null)
            response.getOutputStream().write(encodedOcspResp);
        } // end if (ocspRespWithCacheInfo)
    } catch (EOFException e) {
        final String message = "Connection reset by peer";
        if (LOG.isErrorEnabled()) {
            LOG.warn(LogUtil.buildExceptionLogFormat(message), e.getClass().getName(), e.getMessage());
        }
        LOG.debug(message, e);

        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentLength(0);
    } catch (Throwable t) {
        final String message = "Throwable thrown, this should not happen!";
        LOG.error(message, t);

        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentLength(0);

        auditLevel = AuditLevel.ERROR;
        auditStatus = AuditStatus.FAILED;
        auditMessage = "internal error";
    } finally {
        try {
            response.flushBuffer();
        } finally {
            if (auditEvent != null) {
                if (auditLevel != null) {
                    auditEvent.setLevel(auditLevel);
                }

                if (auditStatus != null) {
                    auditEvent.setStatus(auditStatus);
                }

                if (auditMessage != null) {
                    auditEvent.addEventData(new AuditEventData("message", auditMessage));
                }

                auditEvent.setDuration(System.currentTimeMillis() - start);

                if (auditEvent.containsChildAuditEvents() == false) {
                    auditLoggingService.logEvent(auditEvent);
                } else {
                    List<AuditEvent> expandedAuditEvents = auditEvent.expandAuditEvents();
                    for (AuditEvent event : expandedAuditEvents) {
                        auditLoggingService.logEvent(event);
                    }
                }
            } // end if(auditEvent != null)
        } // end inner try
    } // end external try
}

From source file:org.xipki.pki.ca.api.publisher.x509.X509CertificateInfo.java

License:Open Source License

public X509CertificateInfo(final X509CertWithDbId cert, final X509Cert issuerCert,
        final byte[] subjectPublicKey, final String profileName) throws CertificateEncodingException {
    this.profileName = ParamUtil.requireNonBlank("profileName", profileName);
    this.cert = ParamUtil.requireNonNull("cert", cert);
    this.subjectPublicKey = ParamUtil.requireNonNull("subjectPublicKey", subjectPublicKey);
    this.issuerCert = ParamUtil.requireNonNull("issuerCert", issuerCert);
    ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier(cert.getCert().getSigAlgOID());
    byte[] params = cert.getCert().getSigAlgParams();

    try {//from  w ww. j a v  a 2s.  co  m
        AlgorithmIdentifier algId;
        algId = (params == null) ? new AlgorithmIdentifier(oid)
                : new AlgorithmIdentifier(oid, new ASN1StreamParser(params).readObject());

        AlgorithmIdentifier hashId = AlgorithmUtil.extractDigesetAlgId(algId);
        this.hashAlgo = HashAlgoType.getNonNullHashAlgoType(hashId.getAlgorithm().getId());
    } catch (IllegalArgumentException | IOException | NoSuchAlgorithmException ex) {
        throw new CertificateEncodingException(
                "could not retrieve hash algorithm used to sign the certificate: " + ex.getMessage(), ex);
    }
}

From source file:org.xipki.pki.ca.certprofile.XmlX509Certprofile.java

License:Open Source License

private void initQcStatements(ExtensionsType extensionsType) throws CertprofileException {
    ASN1ObjectIdentifier type = Extension.qCStatements;
    if (!extensionControls.containsKey(type)) {
        return;/*from  w w w. j ava  2 s  .c om*/
    }

    QcStatements extConf = (QcStatements) getExtensionValue(type, extensionsType, QcStatements.class);

    if (extConf == null) {
        return;
    }

    List<QcStatementType> qcStatementTypes = extConf.getQcStatement();

    this.qcStatementsOption = new ArrayList<>(qcStatementTypes.size());
    Set<String> currencyCodes = new HashSet<>();
    boolean requireInfoFromReq = false;

    for (QcStatementType m : qcStatementTypes) {
        ASN1ObjectIdentifier qcStatementId = new ASN1ObjectIdentifier(m.getStatementId().getValue());
        QcStatementOption qcStatementOption;

        QcStatementValueType statementValue = m.getStatementValue();
        if (statementValue == null) {
            QCStatement qcStatment = new QCStatement(qcStatementId);
            qcStatementOption = new QcStatementOption(qcStatment);
        } else if (statementValue.getQcRetentionPeriod() != null) {
            QCStatement qcStatment = new QCStatement(qcStatementId,
                    new ASN1Integer(statementValue.getQcRetentionPeriod()));
            qcStatementOption = new QcStatementOption(qcStatment);
        } else if (statementValue.getConstant() != null) {
            ASN1Encodable constantStatementValue;
            try {
                constantStatementValue = new ASN1StreamParser(statementValue.getConstant().getValue())
                        .readObject();
            } catch (IOException ex) {
                throw new CertprofileException("can not parse the constant value of QcStatement");
            }
            QCStatement qcStatment = new QCStatement(qcStatementId, constantStatementValue);
            qcStatementOption = new QcStatementOption(qcStatment);
        } else if (statementValue.getQcEuLimitValue() != null) {
            QcEuLimitValueType euLimitType = statementValue.getQcEuLimitValue();
            String tmpCurrency = euLimitType.getCurrency().toUpperCase();
            if (currencyCodes.contains(tmpCurrency)) {
                throw new CertprofileException("Duplicated definition of qcStatments with QCEuLimitValue for "
                        + "the currency " + tmpCurrency);
            }

            Iso4217CurrencyCode currency = StringUtil.isNumber(tmpCurrency)
                    ? new Iso4217CurrencyCode(Integer.parseInt(tmpCurrency))
                    : new Iso4217CurrencyCode(tmpCurrency);

            Range2Type r1 = euLimitType.getAmount();
            Range2Type r2 = euLimitType.getExponent();
            if (r1.getMin() == r1.getMax() && r2.getMin() == r2.getMax()) {
                MonetaryValue monetaryValue = new MonetaryValue(currency, r1.getMin(), r2.getMin());
                QCStatement qcStatement = new QCStatement(qcStatementId, monetaryValue);
                qcStatementOption = new QcStatementOption(qcStatement);
            } else {
                MonetaryValueOption monetaryValueOption = new MonetaryValueOption(currency, r1, r2);
                qcStatementOption = new QcStatementOption(qcStatementId, monetaryValueOption);
                requireInfoFromReq = true;
            }
            currencyCodes.add(tmpCurrency);
        } else if (statementValue.getPdsLocations() != null) {
            ASN1EncodableVector vec = new ASN1EncodableVector();
            for (PdsLocationType pl : statementValue.getPdsLocations().getPdsLocation()) {
                ASN1EncodableVector vec2 = new ASN1EncodableVector();
                vec2.add(new DERIA5String(pl.getUrl()));
                String lang = pl.getLanguage();
                if (lang.length() != 2) {
                    throw new RuntimeException("invalid language '" + lang + "'");
                }
                vec2.add(new DERPrintableString(lang));
                DERSequence seq = new DERSequence(vec2);
                vec.add(seq);
            }
            QCStatement qcStatement = new QCStatement(qcStatementId, new DERSequence(vec));
            qcStatementOption = new QcStatementOption(qcStatement);
        } else {
            throw new RuntimeException("unknown value of qcStatment");
        }

        this.qcStatementsOption.add(qcStatementOption);
    } // end for

    if (requireInfoFromReq) {
        return;
    }

    ASN1EncodableVector vec = new ASN1EncodableVector();
    for (QcStatementOption m : qcStatementsOption) {
        if (m.getStatement() == null) {
            throw new RuntimeException("should not reach here");
        }
        vec.add(m.getStatement());
    }
    ASN1Sequence seq = new DERSequence(vec);
    qcStatments = new ExtensionValue(extensionControls.get(type).isCritical(), seq);
    qcStatementsOption = null;
}

From source file:org.xipki.pki.ca.certprofile.XmlX509Certprofile.java

License:Open Source License

private static ASN1Encodable readAsn1Encodable(final byte[] encoded) throws CertprofileException {
    ASN1StreamParser parser = new ASN1StreamParser(encoded);
    try {/*  ww  w .java2 s .co  m*/
        return parser.readObject();
    } catch (IOException ex) {
        throw new CertprofileException("could not parse the constant extension value", ex);
    }
}

From source file:org.xipki.pki.ca.certprofile.XmlX509CertprofileUtil.java

License:Open Source License

public static Map<ASN1ObjectIdentifier, ExtensionValue> buildConstantExtesions(
        final ExtensionsType extensionsType) throws CertprofileException {
    if (extensionsType == null) {
        return null;
    }//from  w  w  w  . j  a v a 2  s .co m

    Map<ASN1ObjectIdentifier, ExtensionValue> map = new HashMap<>();

    for (ExtensionType m : extensionsType.getExtension()) {
        ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier(m.getType().getValue());
        if (Extension.subjectAlternativeName.equals(oid) || Extension.subjectInfoAccess.equals(oid)
                || Extension.biometricInfo.equals(oid)) {
            continue;
        }

        if (m.getValue() == null || !(m.getValue().getAny() instanceof ConstantExtValue)) {
            continue;
        }

        ConstantExtValue extConf = (ConstantExtValue) m.getValue().getAny();
        byte[] encodedValue = extConf.getValue();
        ASN1StreamParser parser = new ASN1StreamParser(encodedValue);
        ASN1Encodable value;
        try {
            value = parser.readObject();
        } catch (IOException ex) {
            throw new CertprofileException("could not parse the constant extension value", ex);
        }
        ExtensionValue extension = new ExtensionValue(m.isCritical(), value);
        map.put(oid, extension);
    }

    if (CollectionUtil.isEmpty(map)) {
        return null;
    }

    return Collections.unmodifiableMap(map);
}

From source file:org.xipki.pki.ca.qa.ExtensionsChecker.java

License:Open Source License

public static Map<ASN1ObjectIdentifier, QaExtensionValue> buildConstantExtesions(
        final ExtensionsType extensionsType) throws CertprofileException {
    if (extensionsType == null) {
        return null;
    }//w w w. j a va  2  s.  c  om

    Map<ASN1ObjectIdentifier, QaExtensionValue> map = new HashMap<>();

    for (ExtensionType m : extensionsType.getExtension()) {
        if (m.getValue() == null || !(m.getValue().getAny() instanceof ConstantExtValue)) {
            continue;
        }

        ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier(m.getType().getValue());
        if (Extension.subjectAlternativeName.equals(oid) || Extension.subjectInfoAccess.equals(oid)
                || Extension.biometricInfo.equals(oid)) {
            continue;
        }

        ConstantExtValue extConf = (ConstantExtValue) m.getValue().getAny();
        byte[] encodedValue = extConf.getValue();
        ASN1StreamParser parser = new ASN1StreamParser(encodedValue);
        try {
            parser.readObject();
        } catch (IOException ex) {
            throw new CertprofileException("could not parse the constant extension value", ex);
        }
        QaExtensionValue extension = new QaExtensionValue(m.isCritical(), encodedValue);
        map.put(oid, extension);
    }

    if (CollectionUtil.isEmpty(map)) {
        return null;
    }

    return Collections.unmodifiableMap(map);
}

From source file:org.xipki.pki.ocsp.server.impl.HttpOcspServlet.java

License:Open Source License

private void processRequest(final HttpServletRequest request, final HttpServletResponse response,
        final ResponderAndRelativeUri respAndUri, final boolean getMethod)
        throws ServletException, IOException {
    Responder responder = respAndUri.getResponder();
    AuditEvent event = null;/*from  w w w. j ava  2  s  . c o m*/
    AuditLevel auditLevel = AuditLevel.INFO;
    AuditStatus auditStatus = AuditStatus.SUCCESSFUL;
    String auditMessage = null;

    AuditService auditService = (auditServiceRegister == null) ? null : auditServiceRegister.getAuditService();

    if (responder.getAuditOption() != null) {
        event = new AuditEvent(new Date());
        event.setApplicationName(OcspAuditConstants.APPNAME);
        event.setName(OcspAuditConstants.NAME_PERF);
    }

    try {
        if (server == null) {
            String message = "responder in servlet not configured";
            LOG.error(message);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.setContentLength(0);

            auditLevel = AuditLevel.ERROR;
            auditStatus = AuditStatus.FAILED;
            auditMessage = message;
            return;
        }

        InputStream requestStream;
        if (getMethod) {
            String relativeUri = respAndUri.getRelativeUri();

            // RFC2560 A.1.1 specifies that request longer than 255 bytes SHOULD be sent by
            // POST, we support GET for longer requests anyway.
            if (relativeUri.length() > responder.getRequestOption().getMaxRequestSize()) {
                response.setContentLength(0);
                response.setStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);

                auditStatus = AuditStatus.FAILED;
                auditMessage = "request too large";
                return;
            }

            requestStream = new ByteArrayInputStream(Base64.decode(relativeUri));
        } else {
            // accept only "application/ocsp-request" as content type
            if (!CT_REQUEST.equalsIgnoreCase(request.getContentType())) {
                response.setContentLength(0);
                response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);

                auditStatus = AuditStatus.FAILED;
                auditMessage = "unsupported media type " + request.getContentType();
                return;
            }

            // request too long
            if (request.getContentLength() > responder.getRequestOption().getMaxRequestSize()) {
                response.setContentLength(0);
                response.setStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);

                auditStatus = AuditStatus.FAILED;
                auditMessage = "request too large";
                return;
            } // if (CT_REQUEST)

            requestStream = request.getInputStream();
        } // end if (getMethod)

        OCSPRequest ocspRequest;
        try {
            ASN1StreamParser parser = new ASN1StreamParser(requestStream);
            ocspRequest = OCSPRequest.getInstance(parser.readObject());
        } catch (Exception ex) {
            response.setContentLength(0);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);

            auditStatus = AuditStatus.FAILED;
            auditMessage = "bad request";

            LogUtil.error(LOG, ex, "could not parse the request (OCSPRequest)");
            return;
        }

        OCSPReq ocspReq = new OCSPReq(ocspRequest);

        response.setContentType(HttpOcspServlet.CT_RESPONSE);

        OcspRespWithCacheInfo ocspRespWithCacheInfo = server.answer(responder, ocspReq, getMethod, event);
        if (ocspRespWithCacheInfo == null) {
            auditMessage = "processRequest returned null, this should not happen";
            LOG.error(auditMessage);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.setContentLength(0);

            auditLevel = AuditLevel.ERROR;
            auditStatus = AuditStatus.FAILED;
        } else {
            OCSPResp resp = ocspRespWithCacheInfo.getResponse();
            byte[] encodedOcspResp = null;
            response.setStatus(HttpServletResponse.SC_OK);

            ResponseCacheInfo cacheInfo = ocspRespWithCacheInfo.getCacheInfo();
            if (getMethod && cacheInfo != null) {
                encodedOcspResp = resp.getEncoded();
                long now = System.currentTimeMillis();
                // RFC 5019 6.2: Date: The date and time at which the OCSP server generated
                // the HTTP response.
                response.setDateHeader("Date", now);
                // RFC 5019 6.2: Last-Modified: date and time at which the OCSP responder
                // last modified the response.
                response.setDateHeader("Last-Modified", cacheInfo.getThisUpdate());
                // RFC 5019 6.2: Expires: This date and time will be the same as the
                // nextUpdate time-stamp in the OCSP
                // response itself.
                // This is overridden by max-age on HTTP/1.1 compatible components
                if (cacheInfo.getNextUpdate() != null) {
                    response.setDateHeader("Expires", cacheInfo.getNextUpdate());
                }
                // RFC 5019 6.2: This profile RECOMMENDS that the ETag value be the ASCII
                // HEX representation of the SHA1 hash of the OCSPResponse structure.
                response.setHeader("ETag", new StringBuilder(42).append('\\')
                        .append(HashAlgoType.SHA1.hexHash(encodedOcspResp)).append('\\').toString());

                // Max age must be in seconds in the cache-control header
                long maxAge;
                if (responder.getResponseOption().getCacheMaxAge() != null) {
                    maxAge = responder.getResponseOption().getCacheMaxAge().longValue();
                } else {
                    maxAge = OcspServer.DFLT_CACHE_MAX_AGE;
                }

                if (cacheInfo.getNextUpdate() != null) {
                    maxAge = Math.min(maxAge, (cacheInfo.getNextUpdate() - cacheInfo.getThisUpdate()) / 1000);
                }

                response.setHeader("Cache-Control", new StringBuilder(55).append("max-age=").append(maxAge)
                        .append(",public,no-transform,must-revalidate").toString());
            } // end if (getMethod && cacheInfo != null)

            if (encodedOcspResp != null) {
                response.getOutputStream().write(encodedOcspResp);
            } else {
                ASN1OutputStream asn1Out = new ASN1OutputStream(response.getOutputStream());
                asn1Out.writeObject(resp.toASN1Structure());
                asn1Out.flush();
            }
        } // end if (ocspRespWithCacheInfo)
    } catch (EOFException ex) {
        LogUtil.warn(LOG, ex, "Connection reset by peer");
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentLength(0);
    } catch (Throwable th) {
        final String message = "Throwable thrown, this should not happen!";
        LogUtil.error(LOG, th, message);

        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentLength(0);

        auditLevel = AuditLevel.ERROR;
        auditStatus = AuditStatus.FAILED;
        auditMessage = "internal error";
    } finally {
        try {
            response.flushBuffer();
        } catch (IOException ex) {
            final String message = "error while calling responsse.flushBuffer";
            LogUtil.error(LOG, ex, message);
            auditLevel = AuditLevel.ERROR;
            auditStatus = AuditStatus.FAILED;
            auditMessage = "internal error";
        } finally {
            if (event != null) {
                if (auditLevel != null) {
                    event.setLevel(auditLevel);
                }

                if (auditStatus != null) {
                    event.setStatus(auditStatus);
                }

                if (auditMessage != null) {
                    event.addEventData(OcspAuditConstants.NAME_message, auditMessage);
                }

                event.finish();
                auditService.logEvent(event);
            }
        } // end internal try
    } // end external try
}

From source file:test.unit.be.fedict.eid.applet.service.signer.CMSTest.java

License:Open Source License

/**
 * CMS signature with external data and external certificate. The CMS only
 * contains the signature and some certificate selector.
 * //from  w  w  w  .j a  v  a  2  s.c  o  m
 * @throws Exception
 */
@Test
public void testBasicCmsSignature() throws Exception {
    // setup
    KeyPair keyPair = PkiTestUtils.generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusMonths(1);
    X509Certificate certificate = generateSelfSignedCertificate(keyPair, "CN=Test", notBefore, notAfter);
    byte[] toBeSigned = "hello world".getBytes();

    // operate
    CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
    generator.addSigner(keyPair.getPrivate(), certificate, CMSSignedDataGenerator.DIGEST_SHA1);
    CMSProcessable content = new CMSProcessableByteArray(toBeSigned);
    CMSSignedData signedData = generator.generate(content, false, (String) null);

    byte[] cmsSignature = signedData.getEncoded();
    LOG.debug("CMS signature: " + ASN1Dump.dumpAsString(new ASN1StreamParser(cmsSignature).readObject()));

    // verify
    signedData = new CMSSignedData(content, cmsSignature);
    SignerInformationStore signers = signedData.getSignerInfos();
    Iterator<SignerInformation> iter = signers.getSigners().iterator();
    while (iter.hasNext()) {
        SignerInformation signer = iter.next();
        SignerId signerId = signer.getSID();
        LOG.debug("signer: " + signerId);
        assertTrue(signerId.match(certificate));
        assertTrue(signer.verify(keyPair.getPublic(), BouncyCastleProvider.PROVIDER_NAME));
    }
    LOG.debug("content type: " + signedData.getSignedContentTypeOID());
}