List of usage examples for org.bouncycastle.tsp TimeStampResponse TimeStampResponse
TimeStampResponse(DLSequence dlSequence) throws TSPException, IOException
From source file:org.signserver.server.cryptotokens.P11SignTest.java
License:Open Source License
private void tsSigner() throws Exception { // Generate CSR PKCS10CertReqInfo certReqInfo = new PKCS10CertReqInfo("SHA1WithRSA", "CN=Worker" + WORKER_TSA, null); Base64SignerCertReqData reqData = (Base64SignerCertReqData) getWorkerSession() .getCertificateRequest(WORKER_TSA, certReqInfo, false); // Issue certificate PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Base64.decode(reqData.getBase64CertReq())); KeyPair issuerKeyPair = CryptoUtils.generateRSA(512); X509CertificateHolder cert = new X509v3CertificateBuilder(new X500Name("CN=TestP11 Issuer"), BigInteger.ONE, new Date(), new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(365)), csr.getSubject(), csr.getSubjectPublicKeyInfo()) .addExtension(org.bouncycastle.asn1.x509.X509Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_timeStamping)) .build(new JcaContentSignerBuilder("SHA256WithRSA").setProvider("BC") .build(issuerKeyPair.getPrivate())); // Install certificate and chain workerSession.uploadSignerCertificate(WORKER_TSA, cert.getEncoded(), GlobalConfiguration.SCOPE_GLOBAL); workerSession.uploadSignerCertificateChain(WORKER_TSA, Arrays.asList(cert.getEncoded()), GlobalConfiguration.SCOPE_GLOBAL); workerSession.reloadConfiguration(WORKER_TSA); // Test active List<String> errors = workerSession.getStatus(WORKER_TSA).getFatalErrors(); assertEquals("errors: " + errors, 0, errors.size()); // Test signing TimeStampRequestGenerator timeStampRequestGenerator = new TimeStampRequestGenerator(); TimeStampRequest timeStampRequest = timeStampRequestGenerator.generate(TSPAlgorithms.SHA1, new byte[20], BigInteger.valueOf(100)); byte[] requestBytes = timeStampRequest.getEncoded(); GenericSignRequest signRequest = new GenericSignRequest(567, requestBytes); final GenericSignResponse res = (GenericSignResponse) workerSession.process(WORKER_TSA, signRequest, new RequestContext()); Certificate signercert = res.getSignerCertificate(); assertNotNull(signercert);/*from www. ja va 2s .c om*/ final TimeStampResponse timeStampResponse = new TimeStampResponse((byte[]) res.getProcessedData()); timeStampResponse.validate(timeStampRequest); assertEquals("Token granted", PKIStatus.GRANTED, timeStampResponse.getStatus()); assertNotNull("Got timestamp token", timeStampResponse.getTimeStampToken()); }
From source file:org.signserver.server.tsa.InternalTimeStampTokenFetcher.java
License:Open Source License
public TimeStampToken fetchToken(byte[] imprint, ASN1ObjectIdentifier digestOID) throws IllegalRequestException, CryptoTokenOfflineException, SignServerException, TSPException, IOException { int workerId; try {// w ww .j av a2 s . co m workerId = Integer.parseInt(workerNameOrId); } catch (NumberFormatException ex) { if (LOG.isDebugEnabled()) { LOG.debug("Not a workerId, maybe workerName: " + workerNameOrId); } workerId = session.getWorkerId(workerNameOrId); } // Setup the time stamp request TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator(); tsqGenerator.setCertReq(true); BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis()); TimeStampRequest request = tsqGenerator.generate(digestOID, imprint, nonce); byte[] requestBytes = request.getEncoded(); final RequestContext context = new RequestContext(); if (username != null && password != null) { context.put(RequestContext.CLIENT_CREDENTIAL, new UsernamePasswordClientCredential(username, password)); } final ProcessResponse resp = session.process(workerId, new GenericSignRequest(hashCode(), requestBytes), context); if (resp instanceof GenericSignResponse) { final byte[] respBytes = ((GenericSignResponse) resp).getProcessedData(); TimeStampResponse response = new TimeStampResponse(respBytes); TimeStampToken tsToken = response.getTimeStampToken(); if (tsToken == null) { throw new SignServerException("TSA '" + workerNameOrId + "' failed to return time stamp token: " + response.getStatusString()); } if (response.getStatus() != PKIStatus.GRANTED && response.getStatus() != PKIStatus.GRANTED_WITH_MODS) { throw new SignServerException("Time stamp token not granted: " + response.getStatusString()); } response.validate(request); return tsToken; } else { throw new SignServerException("Unknown response"); } }
From source file:org.signserver.test.performance.impl.TimeStamp.java
License:Open Source License
/** * Issue a time stamp request./*from w w w .j a va 2s .c om*/ * * @return Run time (in ms). * @throws TSPException * @throws IOException * @throws FailedException */ private long tsaRequest() throws TSPException, IOException, FailedException { final TimeStampRequestGenerator timeStampRequestGenerator = new TimeStampRequestGenerator(); final int nonce = random.nextInt(); byte[] digest = new byte[20]; final TimeStampRequest timeStampRequest = timeStampRequestGenerator.generate(TSPAlgorithms.SHA1, digest, BigInteger.valueOf(nonce)); final byte[] requestBytes = timeStampRequest.getEncoded(); URL url; URLConnection urlConn; DataOutputStream printout; DataInputStream input; url = new URL(tsaUrl); // 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()); byte[] ba = null; final ByteArrayOutputStream baos = new ByteArrayOutputStream(); do { if (ba != null) { baos.write(ba); } ba = new byte[input.available()]; } while (input.read(ba) != -1); // Take stop time final long estimatedTime = System.nanoTime() - startTime; final long timeInMillis = TimeUnit.NANOSECONDS.toMillis(estimatedTime); if (LOG.isDebugEnabled()) { LOG.debug("Got reply after " + timeInMillis + " ms"); } final byte[] replyBytes = baos.toByteArray(); final TimeStampResponse timeStampResponse = new TimeStampResponse(replyBytes); timeStampResponse.validate(timeStampRequest); LOG.debug("TimeStampResponse validated"); // TODO: Maybe in the future we would like to make the below failure // check configurable or count the failure but without failing the test if (timeStampResponse.getStatus() != PKIStatus.GRANTED && timeStampResponse.getStatus() != PKIStatus.GRANTED_WITH_MODS) { throw new FailedException("Token was not granted. Status was: " + timeStampResponse.getStatus() + " (" + timeStampResponse.getStatusString() + ")"); } else { LOG.debug("TimeStampResponse granted"); } return timeInMillis; }
From source file:org.signserver.test.random.impl.Sign.java
License:Open Source License
private void process(final WorkerSpec signer, final int reqid) throws FailedException, IllegalRequestException, CryptoTokenOfflineException, SignServerException { final ProcessResponse result; final RequestContext requestContext = new RequestContext(); if (preProcessor != null) { preProcessor.preProcess(requestContext); }//from w w w . j a va 2 s . co m switch (signer.getWorkerType()) { case xml: { // Process final GenericSignRequest signRequest = new GenericSignRequest(reqid, TESTXML1.getBytes()); final ProcessResponse response = workerSession.process(signer.getWorkerId(), signRequest, requestContext); // Check result GenericSignResponse res = (GenericSignResponse) response; final byte[] data = res.getProcessedData(); // Check that we got a signed XML back String xml = new String(data); if (!xml.contains("xmldsig")) { throw new FailedException("Response was not signed: \"" + xml + "\""); } validateXMLSignature(xml); break; } case tsa: { try { // Process final TimeStampRequestGenerator timeStampRequestGenerator = new TimeStampRequestGenerator(); final int nonce = random.nextInt(); final TimeStampRequest timeStampRequest = timeStampRequestGenerator.generate(TSPAlgorithms.SHA1, new byte[20], BigInteger.valueOf(nonce)); byte[] requestBytes = timeStampRequest.getEncoded(); GenericSignRequest signRequest = new GenericSignRequest(reqid, requestBytes); final GenericSignResponse res = (GenericSignResponse) workerSession.process(signer.getWorkerId(), signRequest, requestContext); // Check result if (reqid != res.getRequestID()) { throw new FailedException("Expected request id: " + reqid + " but was " + res.getRequestID()); } final Certificate signercert = res.getSignerCertificate(); if (signercert == null) { throw new FailedException("No certificate returned"); } final TimeStampResponse timeStampResponse = new TimeStampResponse((byte[]) res.getProcessedData()); timeStampResponse.validate(timeStampRequest); if (timeStampResponse.getStatus() != PKIStatus.GRANTED) { throw new FailedException("Token was not granted: " + timeStampResponse.getStatus()); } if (timeStampResponse.getTimeStampToken() == null) { throw new FailedException("No token returned"); } break; } catch (TSPException ex) { LOG.error("Verification error", ex); throw new FailedException("Response could not be verified: " + ex.getMessage()); } catch (IOException ex) { LOG.error("Could not create request", ex); throw new FailedException("Could not create request: " + ex.getMessage()); } } default: throw new IllegalRequestException("Unsupported workerType: " + signer.getWorkerType()); } }
From source file:org.votingsystem.signature.util.TimeStampResponseGenerator.java
License:Open Source License
/** @deprecated */ public TimeStampResponse generate(TimeStampRequest request, BigInteger serialNumber, Date genTime, String provider) throws NoSuchAlgorithmException, NoSuchProviderException, TSPException { TimeStampResp resp;// w w w . j a v a 2s . c o m PKIStatusInfo pkiStatusInfo; try { if (genTime == null) { throw new TSPValidationException("The time source is not available.", 512); } request.validate(this.acceptedAlgorithms, this.acceptedPolicies, this.acceptedExtensions, provider); this.status = 0; this.addStatusString("Operation OK"); PKIStatusInfo e = this.getPKIStatusInfo(); pkiStatusInfo = null; ContentInfo pkiStatusInfo1; try { ByteArrayInputStream ioEx = new ByteArrayInputStream(this.tokenGenerator .generate(request, serialNumber, genTime, provider).toCMSSignedData().getEncoded()); ASN1InputStream aIn = new ASN1InputStream(ioEx); pkiStatusInfo1 = ContentInfo.getInstance(aIn.readObject()); } catch (IOException var11) { throw new TSPException("Timestamp token received cannot be converted to ContentInfo", var11); } resp = new TimeStampResp(e, pkiStatusInfo1); } catch (TSPValidationException var12) { this.status = 2; this.setFailInfoField(var12.getFailureCode()); this.addStatusString(var12.getMessage()); pkiStatusInfo = this.getPKIStatusInfo(); resp = new TimeStampResp(pkiStatusInfo, (ContentInfo) null); } try { return new TimeStampResponse(resp); } catch (IOException var10) { throw new TSPException("created badly formatted response!"); } }
From source file:org.votingsystem.signature.util.TimeStampResponseGenerator.java
License:Open Source License
public TimeStampResponse generate(TimeStampRequest request, BigInteger serialNumber, Date genTime) throws TSPException { this.statusStrings = new ASN1EncodableVector(); TimeStampResp resp;/*from www. j av a 2s . c o m*/ PKIStatusInfo pkiStatusInfo; try { if (genTime == null) { throw new TSPValidationException("The time source is not available.", 512); } request.validate(this.acceptedAlgorithms, this.acceptedPolicies, this.acceptedExtensions); this.status = 0; this.addStatusString("Operation Okay"); PKIStatusInfo e = this.getPKIStatusInfo(); pkiStatusInfo = null; ContentInfo pkiStatusInfo1; try { ByteArrayInputStream ioEx = new ByteArrayInputStream(this.tokenGenerator .generate(request, serialNumber, genTime).toCMSSignedData().getEncoded()); ASN1InputStream aIn = new ASN1InputStream(ioEx); pkiStatusInfo1 = ContentInfo.getInstance(aIn.readObject()); } catch (IOException var10) { throw new TSPException("Timestamp token received cannot be converted to ContentInfo", var10); } resp = new TimeStampResp(e, pkiStatusInfo1); } catch (TSPValidationException var11) { this.status = 2; this.setFailInfoField(var11.getFailureCode()); this.addStatusString(var11.getMessage()); pkiStatusInfo = this.getPKIStatusInfo(); resp = new TimeStampResp(pkiStatusInfo, (ContentInfo) null); } try { return new TimeStampResponse(resp); } catch (IOException var9) { throw new TSPException("created badly formatted response!"); } }
From source file:org.votingsystem.signature.util.TimeStampResponseGenerator.java
License:Open Source License
public TimeStampResponse generateFailResponse(int status, int failInfoField, String statusString) throws TSPException { this.status = status; this.setFailInfoField(failInfoField); if (statusString != null) { this.addStatusString(statusString); }//from w w w . j a v a2 s .c om PKIStatusInfo pkiStatusInfo = this.getPKIStatusInfo(); TimeStampResp resp = new TimeStampResp(pkiStatusInfo, (ContentInfo) null); try { return new TimeStampResponse(resp); } catch (IOException var7) { throw new TSPException("created badly formatted response!"); } }
From source file:test.integ.be.fedict.trust.TSATest.java
License:Open Source License
private void testTimestampServerTrust(String tsaLocation) throws Exception { // setup// ww w . ja va2s . c o m TimeStampRequestGenerator requestGen = new TimeStampRequestGenerator(); requestGen.setCertReq(true); TimeStampRequest request = requestGen.generate(TSPAlgorithms.SHA1, new byte[20], BigInteger.valueOf(100)); byte[] requestData = request.getEncoded(); DefaultHttpClient httpClient = new DefaultHttpClient(); // HttpHost proxy = new HttpHost("proxy.yourict.net", 8080); // httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, // proxy); HttpPost postMethod = new HttpPost(tsaLocation); ContentType contentType = ContentType.create("application/timestamp-query"); HttpEntity requestEntity = new ByteArrayEntity(requestData, contentType); postMethod.addHeader("User-Agent", "jTrust TSP Client"); postMethod.setEntity(requestEntity); // operate long t0 = System.currentTimeMillis(); HttpResponse httpResponse = httpClient.execute(postMethod); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); long t1 = System.currentTimeMillis(); LOG.debug("dt TSP: " + (t1 - t0) + " ms"); if (statusCode != HttpURLConnection.HTTP_OK) { LOG.error("Error contacting TSP server " + TSA_LOCATION); throw new Exception("Error contacting TSP server " + TSA_LOCATION); } HttpEntity httpEntity = httpResponse.getEntity(); TimeStampResponse tspResponse = new TimeStampResponse(httpEntity.getContent()); postMethod.releaseConnection(); TimeStampToken timeStampToken = tspResponse.getTimeStampToken(); SignerId signerId = timeStampToken.getSID(); Store certificatesStore = timeStampToken.getCertificates(); Collection<X509CertificateHolder> signerCollection = certificatesStore.getMatches(signerId); Iterator<X509CertificateHolder> signerCollectionIterator = signerCollection.iterator(); X509CertificateHolder signerCertificateHolder = signerCollectionIterator.next(); // TODO: check time-stamp token signature List<X509Certificate> certificateChain = getCertificateChain(signerCertificateHolder, certificatesStore); for (X509Certificate cert : certificateChain) { LOG.debug("certificate subject: " + cert.getSubjectX500Principal()); LOG.debug("certificate issuer: " + cert.getIssuerX500Principal()); } CertificateRepository certificateRepository = BelgianTrustValidatorFactory.createTSACertificateRepository(); TrustValidator trustValidator = new TrustValidator(certificateRepository); // NetworkConfig networkConfig = new NetworkConfig("proxy.yourict.net", // 8080); TrustValidatorDecorator trustValidatorDecorator = new TrustValidatorDecorator(null); trustValidatorDecorator.addDefaultTrustLinkerConfig(trustValidator); trustValidator.isTrusted(certificateChain); }
From source file:xades4j.providers.impl.DefaultTimeStampTokenProvider.java
License:Open Source License
@Override public final TimeStampTokenRes getTimeStampToken(byte[] tsDigestInput, String digestAlgUri) throws TimeStampTokenGenerationException { try {/*from w ww .j a va 2 s.c o m*/ MessageDigest md = messageDigestProvider.getEngine(digestAlgUri); byte[] digest = md.digest(tsDigestInput); TimeStampRequest tsRequest = this.tsRequestGenerator.generate(identifierForDigest(digestAlgUri), digest, BigInteger.valueOf(System.currentTimeMillis())); InputStream responseStream = getResponse(tsRequest.getEncoded()); TimeStampResponse tsResponse = new TimeStampResponse(responseStream); if (tsResponse.getStatus() != PKIStatus.GRANTED && tsResponse.getStatus() != PKIStatus.GRANTED_WITH_MODS) { throw new TimeStampTokenGenerationException( "Time stamp token not granted. " + tsResponse.getStatusString()); } tsResponse.validate(tsRequest); TimeStampToken tsToken = tsResponse.getTimeStampToken(); return new TimeStampTokenRes(tsToken.getEncoded(), tsToken.getTimeStampInfo().getGenTime()); } catch (UnsupportedAlgorithmException ex) { throw new TimeStampTokenGenerationException("Digest algorithm not supported", ex); } catch (TSPException ex) { throw new TimeStampTokenGenerationException("Invalid time stamp response", ex); } catch (IOException ex) { throw new TimeStampTokenGenerationException("Encoding error", ex); } }
From source file:xmlgenerator.SignDispatch.java
public boolean signTimeStamp() throws SAXException, ParserConfigurationException, IOException { byte[] digest = getSignature().getBytes(); try {// w w w . j a v a2 s .c o m String str = getTimestamp(new String(Base64.encode(digest))); byte[] out = Base64.decode(str.getBytes()); TimeStampResponse tsResponse = new TimeStampResponse(out); TimeStampToken tsToken = tsResponse.getTimeStampToken(); signWithTimeStamp(new String(Base64.encode(tsToken.getEncoded()))); return true; } catch (Exception e) { e.printStackTrace(); } return false; }