List of usage examples for org.bouncycastle.asn1 ASN1OutputStream flush
public void flush() throws IOException
From source file:bft.BFTNode.java
private byte[] encodeBlockHeaderASN1(Common.BlockHeader header) throws IOException { //convert long to byte array //ByteArrayOutputStream bos = new ByteArrayOutputStream(); //ObjectOutput out = new ObjectOutputStream(bos); //out.writeLong(header.getNumber()); //out.flush(); //bos.flush(); //out.close(); //bos.close(); //byte[] number = bos.toByteArray(); // encode the header in ASN1 format ByteArrayOutputStream bos = new ByteArrayOutputStream(); ASN1OutputStream asnos = new ASN1OutputStream(bos); asnos.writeObject(new ASN1Integer((int) header.getNumber())); //asnos.writeObject(new DERInteger((int) header.getNumber())); asnos.writeObject(new DEROctetString(header.getPreviousHash().toByteArray())); asnos.writeObject(new DEROctetString(header.getDataHash().toByteArray())); asnos.flush(); bos.flush();// w w w. java 2s . co m asnos.close(); bos.close(); byte[] buffer = bos.toByteArray(); //Add golang idiosyncrasies byte[] bytes = new byte[buffer.length + 2]; bytes[0] = 48; // no idea what this means, but golang's encoding uses it bytes[1] = (byte) buffer.length; // length of the rest of the octet string, also used by golang for (int i = 0; i < buffer.length; i++) { // concatenate bytes[i + 2] = buffer[i]; } return bytes; }
From source file:net.schmizz.sshj.signature.SignatureDSA.java
License:Apache License
/** * Encodes the signature as a DER sequence (ASN.1 format). *///from www. j a v a 2s .co m private byte[] asnEncode(byte[] sigBlob) throws IOException { byte[] r = new BigInteger(1, Arrays.copyOfRange(sigBlob, 0, 20)).toByteArray(); byte[] s = new BigInteger(1, Arrays.copyOfRange(sigBlob, 20, 40)).toByteArray(); ASN1EncodableVector vector = new ASN1EncodableVector(); vector.add(new ASN1Integer(r)); vector.add(new ASN1Integer(s)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ASN1OutputStream asnOS = new ASN1OutputStream(baos); asnOS.writeObject(new DERSequence(vector)); asnOS.flush(); return baos.toByteArray(); }
From source file:net.schmizz.sshj.signature.SignatureECDSA.java
License:Apache License
/** * Encodes the signature as a DER sequence (ASN.1 format). *///from w ww . jav a 2 s .c o m private byte[] asnEncode(byte[] sigBlob) throws IOException { Buffer.PlainBuffer sigbuf = new Buffer.PlainBuffer(sigBlob); byte[] r = sigbuf.readBytes(); byte[] s = sigbuf.readBytes(); ASN1EncodableVector vector = new ASN1EncodableVector(); vector.add(new ASN1Integer(r)); vector.add(new ASN1Integer(s)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ASN1OutputStream asnOS = new ASN1OutputStream(baos); asnOS.writeObject(new DERSequence(vector)); asnOS.flush(); return baos.toByteArray(); }
From source file:org.ccnx.ccn.impl.security.keystore.AESKeyStoreSpi.java
License:Open Source License
/** * Store the key from _id into a keystore file */// ww w . j av a 2 s . com @Override public void engineStore(OutputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException { if (null == _id) throw new IOException("Key not entered yet"); ASN1OutputStream aos = new ASN1OutputStream(stream); Tuple<SecretKeySpec, SecretKeySpec> keys = initializeForAES(password); try { byte[] iv = new byte[IV_SIZE]; _random.nextBytes(iv); byte[] aesCBC = null; Cipher cipher = Cipher.getInstance(AES_CRYPTO_ALGORITHM); IvParameterSpec ivspec = new IvParameterSpec(iv); cipher.init(Cipher.ENCRYPT_MODE, keys.first(), ivspec); aesCBC = cipher.doFinal(_id); _macKeyMac.init(keys.second()); byte[] checkbuf = new byte[iv.length + aesCBC.length]; System.arraycopy(iv, 0, checkbuf, 0, iv.length); System.arraycopy(aesCBC, 0, checkbuf, iv.length, aesCBC.length); byte[] part3 = _macKeyMac.doFinal(checkbuf); // TODO might be a better way to do this but am not sure how // (and its not really that important anyway) byte[] asn1buf = new byte[iv.length + aesCBC.length + part3.length]; System.arraycopy(checkbuf, 0, asn1buf, 0, checkbuf.length); System.arraycopy(part3, 0, asn1buf, iv.length + aesCBC.length, part3.length); ASN1OctetString os = new DEROctetString(asn1buf); ASN1Encodable[] ae = new ASN1Encodable[3]; ae[0] = _version; ae[1] = _oid; ae[2] = os; DERSequence ds = new DERSequence(ae); aos.writeObject(ds); aos.flush(); aos.close(); } catch (Exception e) { throw new IOException(e); } }
From source file:org.glite.voms.PKIUtils.java
License:Open Source License
/** * Checks if a certificate issued another certificate, according to RFC 3280. * * @param issuer The candidate issuer certificate. * @param issued The candidate issued certificate. * * @return true if <em>issuer</em> issued <em>issued</em>, false othersie. *//*from w ww. jav a2s . c o m*/ static public boolean checkIssued(X509Certificate issuer, X509Certificate issued) { X500Principal issuerSubject = issuer.getSubjectX500Principal(); X500Principal issuedIssuer = issued.getIssuerX500Principal(); if (logger.isDebugEnabled()) { logger.debug("Is: " + issued.getSubjectDN().getName() + " issued by " + issuer.getSubjectDN().getName() + "?"); logger.debug("Is: " + issuedIssuer.getName() + " issued by " + issuerSubject.getName() + "?"); logger.debug( "Is: " + issued.getSubjectDN().getName() + " issued by " + issuer.getSubjectDN().getName()); logger.debug("[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[["); } // try { boolean b = issuerSubject.equals(issuedIssuer); // } // catch(Exception e) { // System.out.println("Caught: " + e.getMessage() + " " + e.getClass()); // } if (issuerSubject.equals(issuedIssuer)) { logger.debug("================================"); logger.debug("issuersSubject = issuedIssuer"); AuthorityKeyIdentifier akid = PKIUtils.getAKID(issued); if (logger.isDebugEnabled()) logger.debug("akid = " + akid); if (akid != null) { logger.debug("Authority Key Identifier extension found in issued certificate."); logger.debug("Entered."); SubjectKeyIdentifier skid = PKIUtils.getSKID(issuer); if (logger.isDebugEnabled()) logger.debug("sid = " + skid); if (skid != null) { logger.debug("subject Key Identifier extensions found in issuer certificate."); logger.debug("comparing skid to akid"); byte[] skidValue = skid.getKeyIdentifier(); if (logger.isDebugEnabled()) { logger.debug("skid"); String str = ""; for (int i = 0; i < skidValue.length; i++) str += Integer.toHexString(skidValue[i]) + " "; logger.debug(str); } byte[] akidValue = akid.getKeyIdentifier(); if (logger.isDebugEnabled()) { logger.debug("akid"); String str = ""; for (int i = 0; i < akidValue.length; i++) str += Integer.toHexString(akidValue[i]) + " "; logger.debug(str); } logger.debug("skid/akid checking."); if (!Arrays.equals(skidValue, akidValue)) return false; logger.debug("skid/akid check passed."); } if (false) { // The following should be skipped if the previous check passed. // And code cannot reach here unless the previous step passed. BigInteger sn = getAuthorityCertificateSerialNumber(akid); // // if (sn == null) { // logger.error("Serial number missing from Authority Key Identifier"); // return false; // } // // if (!sn.equals(issuer.getSerialNumber())) { // logger.error("Serial number in Authority Key Identifier and in issuer certificate do not match"); // logger.error("From akid : " + sn.toString()); // logger.error("From issuer certificate: " + issuer.getSerialNumber()); // return false; // } if (sn != null && !sn.equals(issuer.getSerialNumber())) { logger.error( "Serial number in Authority Key Identifier and in issuer certificate do not match"); logger.error("From akid : " + sn.toString()); logger.error("From issuer certificate: " + issuer.getSerialNumber()); return false; } GeneralNames gns = getAuthorityCertIssuer(akid); if (gns != null) { GeneralName names[] = getNames(gns); // System.out.println("GOT CERTISSUER"); int i = 0; // System.out.println("SIZE = " + names.length); while (i < names.length) { // System.out.println("NAME = " + names[i].getName()); // System.out.println("TAG IS: " + names[i].getTagNo()); if (names[i].getTagNo() == 4) { ASN1Primitive dobj = names[i].getName().toASN1Primitive(); ByteArrayOutputStream baos = null; ASN1OutputStream aos = null; // System.out.println("Inside tag 4"); try { baos = new ByteArrayOutputStream(); aos = new ASN1OutputStream(baos); aos.writeObject(dobj); aos.flush(); } catch (IOException e) { logger.error("Error in encoding of Authority Key Identifier." + e.getMessage()); return false; } X500Principal principal = new X500Principal(baos.toByteArray()); // System.out.println("PRINCIPAL: " + principal); X500Principal issuerIssuer = issuer.getIssuerX500Principal(); if (issuerIssuer.equals(principal)) { logger.debug("PASSED"); break; } else { logger.error( "Issuer Issuer not found among Authority Key Identifier's Certifiacte Issuers."); return false; } } } } } } logger.debug("]]]]]]]]]]]]]]]]]]]]]]]]"); boolean keyUsage[] = issuer.getKeyUsage(); if (!PKIUtils.isCA(issuer)) { if ((keyUsage != null && !keyUsage[digitalSignature]) || !PKIUtils.isProxy(issued)) return false; } logger.debug("CHECK ISSUED PASSED"); return true; } logger.debug("Check Issued failed."); return false; }
From source file:org.sufficientlysecure.keychain.securitytoken.SecurityTokenConnection.java
License:Open Source License
private byte[] encodeSignature(byte[] signature, KeyFormat keyFormat) throws IOException { // Make sure the signature we received is actually the expected number of bytes long! switch (keyFormat.keyFormatType()) { case RSAKeyFormatType: // no encoding necessary int modulusLength = ((RSAKeyFormat) keyFormat).getModulusLength(); if (signature.length != (modulusLength / 8)) { throw new IOException("Bad signature length! Expected " + (modulusLength / 8) + " bytes, got " + signature.length); }/*ww w .j a va 2s.c o m*/ break; case ECKeyFormatType: // "plain" encoding, see https://github.com/open-keychain/open-keychain/issues/2108 if (signature.length % 2 != 0) { throw new IOException("Bad signature length!"); } final byte[] br = new byte[signature.length / 2]; final byte[] bs = new byte[signature.length / 2]; for (int i = 0; i < br.length; ++i) { br[i] = signature[i]; bs[i] = signature[br.length + i]; } final ByteArrayOutputStream baos = new ByteArrayOutputStream(); ASN1OutputStream out = new ASN1OutputStream(baos); out.writeObject(new DERSequence(new ASN1Encodable[] { new ASN1Integer(br), new ASN1Integer(bs) })); out.flush(); signature = baos.toByteArray(); break; } return signature; }
From source file:org.xipki.commons.remotep11.server.HttpProxyServlet.java
License:Open Source License
@Override public void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { try {/*w w w. ja v a2 s. c o m*/ String moduleName = extractModuleName(request); if (moduleName == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } if (localP11CryptServicePool == null) { LOG.error("localP11CryptService in servlet not configured"); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setContentLength(0); return; } if (!CT_REQUEST.equalsIgnoreCase(request.getContentType())) { response.setContentLength(0); response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); response.flushBuffer(); return; } PKIMessage pkiReq; try { pkiReq = generatePkiMessage(request.getInputStream()); } catch (Exception ex) { response.setContentLength(0); response.sendError(HttpServletResponse.SC_BAD_REQUEST); LogUtil.error(LOG, ex, "could not parse the request (PKIMessage)"); return; } PKIMessage pkiResp = responder.processPkiMessage(localP11CryptServicePool, moduleName, pkiReq); response.setContentType(CT_RESPONSE); response.setStatus(HttpServletResponse.SC_OK); ASN1OutputStream asn1Out = new ASN1OutputStream(response.getOutputStream()); asn1Out.writeObject(pkiResp); asn1Out.flush(); } catch (EOFException ex) { LogUtil.warn(LOG, ex, "connection reset by peer"); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setContentLength(0); } catch (Throwable th) { LogUtil.error(LOG, th, "Throwable thrown, this should not happen."); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setContentLength(0); } finally { response.flushBuffer(); } }
From source file:org.xipki.pki.ca.server.impl.cmp.HttpCmpServlet.java
License:Open Source License
@Override public void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { X509Certificate clientCert = ClientCertCache.getTlsClientCert(request, sslCertInHttpHeader); AuditService auditService = auditServiceRegister.getAuditService(); AuditEvent event = new AuditEvent(new Date()); event.setApplicationName(CaAuditConstants.APPNAME); event.setName(CaAuditConstants.NAME_PERF); event.addEventData(CaAuditConstants.NAME_reqType, RequestType.CMP.name()); AuditLevel auditLevel = AuditLevel.INFO; AuditStatus auditStatus = AuditStatus.SUCCESSFUL; String auditMessage = null;//from w w w .j a va 2 s. co m try { if (responderManager == null) { String message = "responderManager in servlet not configured"; LOG.error(message); throw new HttpRespAuditException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message, AuditLevel.ERROR, AuditStatus.FAILED); } if (!CT_REQUEST.equalsIgnoreCase(request.getContentType())) { String message = "unsupported media type " + request.getContentType(); throw new HttpRespAuditException(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, message, AuditLevel.INFO, AuditStatus.FAILED); } String requestUri = request.getRequestURI(); String servletPath = request.getServletPath(); String caName = null; X509CaCmpResponder responder = null; int len = servletPath.length(); if (requestUri.length() > len + 1) { String caAlias = URLDecoder.decode(requestUri.substring(len + 1), "UTF-8"); caName = responderManager.getCaNameForAlias(caAlias); if (caName == null) { caName = caAlias; } caName = caName.toUpperCase(); responder = responderManager.getX509CaCmpResponder(caName); } if (caName == null || responder == null || !responder.isInService()) { String message; if (caName == null) { message = "no CA is specified"; } else if (responder == null) { message = "unknown CA '" + caName + "'"; } else { message = "CA '" + caName + "' is out of service"; } LOG.warn(message); throw new HttpRespAuditException(HttpServletResponse.SC_NOT_FOUND, message, AuditLevel.INFO, AuditStatus.FAILED); } event.addEventData(CaAuditConstants.NAME_CA, responder.getCa().getCaName()); PKIMessage pkiReq; try { pkiReq = generatePkiMessage(request.getInputStream()); } catch (Exception ex) { LogUtil.error(LOG, ex, "could not parse the request (PKIMessage)"); throw new HttpRespAuditException(HttpServletResponse.SC_BAD_REQUEST, "bad request", AuditLevel.INFO, AuditStatus.FAILED); } PKIHeader reqHeader = pkiReq.getHeader(); ASN1OctetString tid = reqHeader.getTransactionID(); String tidStr = Base64.toBase64String(tid.getOctets()); event.addEventData(CaAuditConstants.NAME_tid, tidStr); PKIHeaderBuilder respHeader = new PKIHeaderBuilder(reqHeader.getPvno().getValue().intValue(), reqHeader.getRecipient(), reqHeader.getSender()); respHeader.setTransactionID(tid); PKIMessage pkiResp = responder.processPkiMessage(pkiReq, clientCert, tidStr, event); response.setContentType(HttpCmpServlet.CT_RESPONSE); response.setStatus(HttpServletResponse.SC_OK); ASN1OutputStream asn1Out = new ASN1OutputStream(response.getOutputStream()); asn1Out.writeObject(pkiResp); asn1Out.flush(); } catch (HttpRespAuditException ex) { auditStatus = ex.getAuditStatus(); auditLevel = ex.getAuditLevel(); auditMessage = ex.getAuditMessage(); response.setContentLength(0); response.setStatus(ex.getHttpStatus()); } 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(); } finally { audit(auditService, event, auditLevel, auditStatus, auditMessage); } } }
From source file:org.xipki.pki.ca.server.impl.scep.ScepServlet.java
License:Open Source License
private void service(final HttpServletRequest request, final HttpServletResponse response, final boolean post) throws ServletException, IOException { String requestUri = request.getRequestURI(); String servletPath = request.getServletPath(); int len = servletPath.length(); String scepName = null;//from w w w .j a va2 s . c o m String certProfileName = null; if (requestUri.length() > len + 1) { String scepPath = URLDecoder.decode(requestUri.substring(len + 1), "UTF-8"); if (scepPath.endsWith(CGI_PROGRAM)) { String path = scepPath.substring(0, scepPath.length() - CGI_PROGRAM_LEN); String[] tokens = path.split("/"); if (tokens.length == 2) { scepName = tokens[0]; certProfileName = tokens[1]; } } // end if } // end if if (scepName == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } AuditService auditService = auditServiceRegister.getAuditService(); AuditEvent event = new AuditEvent(new Date()); event.setApplicationName("SCEP"); event.setName(CaAuditConstants.NAME_PERF); event.addEventData(CaAuditConstants.NAME_SCEP_name, scepName + "/" + certProfileName); event.addEventData(CaAuditConstants.NAME_reqType, RequestType.SCEP.name()); String msgId = RandomUtil.nextHexLong(); event.addEventData(CaAuditConstants.NAME_mid, msgId); AuditLevel auditLevel = AuditLevel.INFO; AuditStatus auditStatus = AuditStatus.SUCCESSFUL; String auditMessage = null; try { if (responderManager == null) { auditMessage = "responderManager in servlet not configured"; LOG.error(auditMessage); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setContentLength(0); auditLevel = AuditLevel.ERROR; auditStatus = AuditStatus.FAILED; return; } String realScepName = responderManager.getCaNameForAlias(scepName); if (realScepName != null) { scepName = realScepName; } Scep responder = responderManager.getScep(scepName); if (responder == null || responder.getStatus() != CaStatus.ACTIVE || !responder.supportsCertProfile(certProfileName)) { auditMessage = "unknown SCEP '" + scepName + "/" + certProfileName + "'"; LOG.warn(auditMessage); response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.setContentLength(0); auditStatus = AuditStatus.FAILED; return; } String operation = request.getParameter("operation"); event.addEventData(CaAuditConstants.NAME_SCEP_operation, operation); if ("PKIOperation".equalsIgnoreCase(operation)) { CMSSignedData reqMessage; // parse the request try { byte[] content; if (post) { content = IoUtil.read(request.getInputStream()); } else { String b64 = request.getParameter("message"); content = Base64.decode(b64); } reqMessage = new CMSSignedData(content); } catch (Exception ex) { final String msg = "invalid request"; LogUtil.error(LOG, ex, msg); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.setContentLength(0); auditMessage = msg; auditStatus = AuditStatus.FAILED; return; } ContentInfo ci; try { ci = responder.servicePkiOperation(reqMessage, certProfileName, msgId, event); } catch (MessageDecodingException ex) { final String msg = "could not decrypt and/or verify the request"; LogUtil.error(LOG, ex, msg); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.setContentLength(0); auditMessage = msg; auditStatus = AuditStatus.FAILED; return; } catch (OperationException ex) { ErrorCode code = ex.getErrorCode(); int httpCode; switch (code) { case ALREADY_ISSUED: case CERT_REVOKED: case CERT_UNREVOKED: httpCode = HttpServletResponse.SC_FORBIDDEN; break; case BAD_CERT_TEMPLATE: case BAD_REQUEST: case BAD_POP: case INVALID_EXTENSION: case UNKNOWN_CERT: case UNKNOWN_CERT_PROFILE: httpCode = HttpServletResponse.SC_BAD_REQUEST; break; case NOT_PERMITTED: httpCode = HttpServletResponse.SC_UNAUTHORIZED; break; case SYSTEM_UNAVAILABLE: httpCode = HttpServletResponse.SC_SERVICE_UNAVAILABLE; break; case CRL_FAILURE: case DATABASE_FAILURE: case SYSTEM_FAILURE: httpCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; break; default: httpCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; break; } final String msg = ex.getMessage(); LogUtil.error(LOG, ex, msg); response.setStatus(httpCode); response.setContentLength(0); auditMessage = msg; auditStatus = AuditStatus.FAILED; return; } response.setContentType(CT_RESPONSE); ASN1OutputStream asn1Out = new ASN1OutputStream(response.getOutputStream()); asn1Out.writeObject(ci); asn1Out.flush(); } else if (Operation.GetCACaps.getCode().equalsIgnoreCase(operation)) { // CA-Ident is ignored response.setContentType(ScepConstants.CT_TEXT_PLAIN); byte[] caCapsBytes = responder.getCaCaps().getBytes(); response.getOutputStream().write(caCapsBytes); } else if (Operation.GetCACert.getCode().equalsIgnoreCase(operation)) { // CA-Ident is ignored byte[] respBytes = responder.getCaCertResp().getBytes(); response.setContentType(ScepConstants.CT_X509_CA_RA_CERT); response.setContentLength(respBytes.length); response.getOutputStream().write(respBytes); } else if (Operation.GetNextCACert.getCode().equalsIgnoreCase(operation)) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.setContentLength(0); auditMessage = "SCEP operation '" + operation + "' is not permitted"; auditStatus = AuditStatus.FAILED; return; } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.setContentLength(0); auditMessage = "unknown SCEP operation '" + operation + "'"; auditStatus = AuditStatus.FAILED; return; } } catch (EOFException ex) { final String msg = "connection reset by peer"; if (LOG.isWarnEnabled()) { LogUtil.warn(LOG, ex, msg); } LOG.debug(msg, ex); 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(); } finally { audit(auditService, event, auditLevel, auditStatus, auditMessage); } } }
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 .ja v a 2 s . com*/ 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 }