List of usage examples for org.bouncycastle.tsp TimeStampRequest TimeStampRequest
public TimeStampRequest(InputStream in) throws IOException
From source file:org.digidoc4j.SkDataLoaderTest.java
License:GNU General Public License
@Test public void getTimestampViaSpy() throws Exception { stubFor(post(urlEqualTo("/")).willReturn(aResponse().proxiedFrom(configuration.getTspSource()))); byte[] tsRequest = new byte[] { 48, 57, 2, 1, 1, 48, 49, 48, 13, 6, 9, 96, -122, 72, 1, 101, 3, 4, 2, 1, 5, 0, 4, 32, 2, 91, 64, 111, 35, -23, -19, -46, 57, -80, -63, -80, -74, 100, 72, 97, -47, -17, -35, -62, 102, 52, 116, 73, -10, -120, 115, 62, 2, 87, -29, -21, 1, 1, -1 }; SkDataLoader dataLoader = SkDataLoader.createTimestampDataLoader(configuration); dataLoader.setUserAgentSignatureProfile(SignatureProfile.LT); byte[] response = dataLoader.post(MOCK_PROXY_URL, tsRequest); assertNotNull(response);/*from ww w . j a v a 2s. c o m*/ TimeStampResponse timeStampResponse = new TimeStampResponse(response); assertEquals(0, timeStampResponse.getStatus()); timeStampResponse.validate(new TimeStampRequest(tsRequest)); verify(postRequestedFor(urlMatching("/")) .withHeader("Content-Type", containing("application/timestamp-query")) .withHeader("User-Agent", containing("LIB DigiDoc4j"))); }
From source file:org.signserver.client.cli.defaultimpl.TimeStampCommand.java
License:Open Source License
private void tsaPrintQuery() throws Exception { final byte[] bytes = readFiletoBuffer(inreqstring); final TimeStampRequest request; out.println("Time-stamp request {"); request = new TimeStampRequest(bytes); out.println(" Version: " + request.getVersion()); out.print(" Message imprint digest: "); out.println(new String(Hex.encode(request.getMessageImprintDigest()))); out.print(" Message imprint algorithm: "); out.println(request.getMessageImprintAlgOID()); out.print(" Policy: "); out.println(request.getReqPolicy() != null ? request.getReqPolicy() : "(null)"); out.print(" Nonce: "); out.println(request.getNonce() != null ? request.getNonce().toString(16) : "(null)"); out.print(" Request certificates: "); out.println(request.getCertReq());// w w w . j ava2s . c o m if (request.hasExtensions()) { out.print(" Extensions: "); for (Object oid : request.getExtensionOIDs()) { if (oid instanceof String) { out.print(" " + oid + ": "); out.println(new String(Hex.encode(request.getExtensionValue((String) oid)))); } } } out.println("}"); }
From source file:org.signserver.client.cli.defaultimpl.TimeStampCommand.java
License:Open Source License
@SuppressWarnings("SleepWhileInLoop") // We are just using the sleep for rate limiting private void tsaRequest() throws Exception { final Random rand = new Random(); final TimeStampRequestGenerator timeStampRequestGenerator = new TimeStampRequestGenerator(); boolean doRun = true; do {/*from w w w . j a v a 2s . c om*/ final int nonce = rand.nextInt(); byte[] digest = new byte[20]; if (instring != null) { final byte[] digestBytes = instring.getBytes("UTF-8"); final MessageDigest dig = MessageDigest.getInstance(TSPAlgorithms.SHA1.getId(), "BC"); dig.update(digestBytes); digest = dig.digest(); // When we have given input, we don't want to loop doRun = false; } if (infilestring != null) { // TSPAlgorithms constants changed from Strings to ASN1Encoded objects digest = digestFile(infilestring, TSPAlgorithms.SHA1.getId()); doRun = false; } final byte[] hexDigest = Hex.encode(digest); if (LOG.isDebugEnabled()) { LOG.debug("MessageDigest=" + new String(hexDigest)); } final TimeStampRequest timeStampRequest; if (inreqstring == null) { LOG.debug("Generating a new request"); timeStampRequestGenerator.setCertReq(certReq); if (reqPolicy != null) { timeStampRequestGenerator.setReqPolicy(new ASN1ObjectIdentifier(reqPolicy)); } timeStampRequest = timeStampRequestGenerator.generate(TSPAlgorithms.SHA1, digest, BigInteger.valueOf(nonce)); } else { LOG.debug("Reading request from file"); timeStampRequest = new TimeStampRequest(readFiletoBuffer(inreqstring)); } final byte[] requestBytes = timeStampRequest.getEncoded(); if (outreqstring != null) { // Store request byte[] outBytes; if (base64) { outBytes = Base64.encode(requestBytes); } else { outBytes = requestBytes; } FileOutputStream fos = null; try { fos = new FileOutputStream(outreqstring); fos.write(outBytes); } finally { if (fos != null) { fos.close(); } } } keyStoreOptions.setupHTTPS(); URL url; URLConnection urlConn; DataOutputStream printout; DataInputStream input; url = new URL(urlstring); // Take start time final long startMillis = System.currentTimeMillis(); final long startTime = System.nanoTime(); if (LOG.isDebugEnabled()) { LOG.debug("Sending request at: " + startMillis); } urlConn = url.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-Type", "application/timestamp-query"); // Send POST output. printout = new DataOutputStream(urlConn.getOutputStream()); printout.write(requestBytes); printout.flush(); printout.close(); // Get response data. input = new DataInputStream(urlConn.getInputStream()); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); int b; while ((b = input.read()) != -1) { baos.write(b); } // Take stop time final long estimatedTime = System.nanoTime() - startTime; LOG.info("Got reply after " + TimeUnit.NANOSECONDS.toMillis(estimatedTime) + " ms"); final byte[] replyBytes = baos.toByteArray(); if (outrepstring != null) { // Store request byte[] outBytes; if (base64) { outBytes = Base64.encode(replyBytes); } else { outBytes = replyBytes; } FileOutputStream fos = null; try { fos = new FileOutputStream(outrepstring); fos.write(outBytes); } finally { if (fos != null) { fos.close(); } } } final TimeStampResponse timeStampResponse = new TimeStampResponse(replyBytes); timeStampResponse.validate(timeStampRequest); LOG.info("TimeStampRequest validated"); if (LOG.isDebugEnabled()) { final Date genTime; if (timeStampResponse.getTimeStampToken() != null && timeStampResponse.getTimeStampToken().getTimeStampInfo() != null) { genTime = timeStampResponse.getTimeStampToken().getTimeStampInfo().getGenTime(); } else { genTime = null; } LOG.debug("(Status: " + timeStampResponse.getStatus() + ", " + timeStampResponse.getFailInfo() + "): " + timeStampResponse.getStatusString() + (genTime != null ? (", genTime: " + genTime.getTime()) : "") + "\n"); } if (doRun) { Thread.sleep(sleep); } } while (doRun); }
From source file:org.signserver.module.tsa.RequestedPolicyDispatcher.java
License:Open Source License
@Override public ProcessResponse processData(final ProcessRequest signRequest, final RequestContext context) throws IllegalRequestException, CryptoTokenOfflineException, SignServerException { final GenericSignResponse result; // Log values final LogMap logMap = LogMap.getInstance(context); // Check context final RequestContext nextContext = context; if (context.get(this.getClass().getName()) != null) { throw new SignServerException("Dispatcher called more then one time for the same request. Aborting."); } else {/* w w w .jav a 2 s . c o m*/ context.put(this.getClass().getName(), "called"); } // Check that the request contains a valid TimeStampRequest object. if (!(signRequest instanceof GenericSignRequest)) { throw new IllegalRequestException("Recieved request wasn't a expected GenericSignRequest."); } final ISignRequest sReq = (ISignRequest) signRequest; // Get TimeStampRequest final TimeStampRequest timeStampRequest; if (sReq.getRequestData() instanceof TimeStampRequest) { timeStampRequest = (TimeStampRequest) sReq.getRequestData(); } else if (sReq.getRequestData() instanceof byte[]) { try { timeStampRequest = new TimeStampRequest((byte[]) sReq.getRequestData()); } catch (IOException ex) { throw new IllegalRequestException("Could not parse TimeStampRequest", ex); } } else { throw new IllegalRequestException("Expected a TimeStampRequest"); } try { // Add to context if (timeStampRequest.getReqPolicy() != null) { nextContext.put(TSA_REQUESTEDPOLICYOID, timeStampRequest.getReqPolicy().getId()); } // Find to which worker the request should be dispatched final String toWorker = lookupWorkerToDispatchTo(timeStampRequest, context); if (toWorker == null) { final TimeStampResponseGenerator gen = new TimeStampResponseGenerator(null, null); final String statusString = includeStatusString ? "request contains unknown policy." : null; final TimeStampResponse resp = gen.generateFailResponse(PKIStatus.REJECTION, PKIFailureInfo.unacceptedPolicy, statusString); // Auditlog logMap.put(IWorkerLogger.LOG_CLIENT_AUTHORIZED, "false"); logMap.put(IWorkerLogger.LOG_EXCEPTION, "requested policy not supported"); result = new GenericServletResponse(sReq.getRequestID(), resp.getEncoded(), null, null, null, RESPONSE_CONTENT_TYPE); } else { int toWorkerId = 0; try { toWorkerId = Integer.parseInt(toWorker); } catch (NumberFormatException ignored) { } if (toWorkerId < 1) { toWorkerId = getWorkerSession().getWorkerId(toWorker); } // Mark request comming from a dispatcher so the DispatchedAuthorizer can be used context.put(RequestContext.DISPATCHER_AUTHORIZED_CLIENT, true); HttpServletRequest httpRequest = null; if (sReq instanceof GenericServletRequest) { httpRequest = ((GenericServletRequest) sReq).getHttpServletRequest(); } ProcessRequest newRequest = new GenericServletRequest(sReq.getRequestID(), (byte[]) sReq.getRequestData(), httpRequest); result = (GenericSignResponse) getWorkerSession().process(toWorkerId, newRequest, context); } } catch (IOException e) { logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, e.getMessage()); throw new SignServerException("Response message could not be constructed", e); } catch (TSPException e) { throw new SignServerException("Response message could not be constructed", e); } return result; }
From source file:org.signserver.module.tsa.TimeStampSignerTest.java
License:Open Source License
/** * Test that a timestamp token is not granted for an policy not listed in * ACCEPTEDPOLICIES and that a proper resoonse is sent back. * @throws Exception in case of exception *//*w ww . java 2s . c o m*/ @Test public void test03NotAcceptedPolicy() throws Exception { // WORKER2 has ACCEPTEDPOLICIES=1.2.3 // Create an request with another policy (1.2.3.5 != 1.2.3) final TimeStampRequest timeStampRequest = new TimeStampRequest( Base64.decode(REQUEST_WITH_POLICY1235.getBytes())); final byte[] requestBytes = timeStampRequest.getEncoded(); final GenericSignRequest signRequest = new GenericSignRequest(13, requestBytes); final GenericSignResponse res = (GenericSignResponse) workerSession.process(WORKER2, signRequest, new RequestContext()); final TimeStampResponse timeStampResponse = new TimeStampResponse((byte[]) res.getProcessedData()); timeStampResponse.validate(timeStampRequest); LOG.info("Response: " + timeStampResponse.getStatusString()); assertEquals("Token rejected", PKIStatus.REJECTION, timeStampResponse.getStatus()); }
From source file:org.signserver.module.tsa.TimeStampSignerTest.java
License:Open Source License
/** * Test that the default behavior on rejection is to include a status string. * @throws Exception/*from w w w . ja v a 2s . c o m*/ */ @Test public void test27StatusStringIncludedFailure() throws Exception { // WORKER2 has ACCEPTEDPOLICIES=1.2.3 // Create an request with another policy (1.2.3.5 != 1.2.3) final TimeStampRequest timeStampRequest = new TimeStampRequest( Base64.decode(REQUEST_WITH_POLICY1235.getBytes())); final byte[] requestBytes = timeStampRequest.getEncoded(); final GenericSignRequest signRequest = new GenericSignRequest(13, requestBytes); final GenericSignResponse res = (GenericSignResponse) workerSession.process(WORKER2, signRequest, new RequestContext()); final TimeStampResponse timeStampResponse = new TimeStampResponse((byte[]) res.getProcessedData()); assertNotNull(timeStampResponse.getStatusString()); }
From source file:org.signserver.module.tsa.TimeStampSignerTest.java
License:Open Source License
/** * Test that setting the INCLUDESTATUSSTRING property to false results in no status string * on rejection./*ww w . jav a2 s . co m*/ * @throws Exception */ @Test public void test28StatusStringExcludedFailure() throws Exception { workerSession.setWorkerProperty(WORKER2, TimeStampSigner.INCLUDESTATUSSTRING, "FALSE"); workerSession.reloadConfiguration(WORKER2); // WORKER2 has ACCEPTEDPOLICIES=1.2.3 // Create an request with another policy (1.2.3.5 != 1.2.3) final TimeStampRequest timeStampRequest = new TimeStampRequest( Base64.decode(REQUEST_WITH_POLICY1235.getBytes())); final byte[] requestBytes = timeStampRequest.getEncoded(); final GenericSignRequest signRequest = new GenericSignRequest(13, requestBytes); final GenericSignResponse res = (GenericSignResponse) workerSession.process(WORKER2, signRequest, new RequestContext()); final TimeStampResponse timeStampResponse = new TimeStampResponse((byte[]) res.getProcessedData()); assertNull(timeStampResponse.getStatusString()); }
From source file:org.votingsystem.signature.util.TimeStampResponseGenerator.java
License:Open Source License
public TimeStampResponseGenerator(InputStream requestInputStream, SignatureData signingData, Date timeStampDate) throws ExceptionVS, OperatorCreationException, CertificateEncodingException, TSPException { TimeStampRequest timeStampRequest;//w w w .j av a2s. c o m try { timeStampRequest = new TimeStampRequest(requestInputStream); } catch (Exception ex) { throw new ExceptionVS("request null"); } this.statusStrings = new ASN1EncodableVector(); serialNumber = KeyGeneratorVS.INSTANCE.getSerno(); log.info("getTimeStampResponse - serialNumber: " + serialNumber + " - CertReq: " + timeStampRequest.getCertReq()); JcaSignerInfoGeneratorBuilder infoGeneratorBuilder = new JcaSignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder().setProvider(ContextVS.PROVIDER).build()); tokenGenerator = new TimeStampTokenGenerator( infoGeneratorBuilder.build(new JcaContentSignerBuilder(SIGNATURE_ALGORITHM) .setProvider(ContextVS.PROVIDER).build(signingData.getSigningKey()), signingData.getSigningCert()), new ASN1ObjectIdentifier(DEFAULT_TSA_POLICY_OID)); tokenGenerator.setAccuracyMicros(ACCURACYMICROS); tokenGenerator.setAccuracyMillis(ACCURACYMILLIS); tokenGenerator.setAccuracySeconds(ACCURACYSECONDS); tokenGenerator.setOrdering(ORDERING); tokenGenerator.addCertificates(signingData.getCerts()); token = tokenGenerator.generate(timeStampRequest, serialNumber, timeStampDate); }