List of usage examples for org.bouncycastle.tsp TimeStampToken getTimeStampInfo
public TimeStampTokenInfo getTimeStampInfo()
From source file:eu.europa.esig.dss.cades.validation.CAdESSignature.java
License:Open Source License
/** * Remove any archive-timestamp-v2/3 attribute added after the * timestampToken//from w w w . j a va 2 s .com */ private ASN1Sequence filterUnauthenticatedAttributes(ASN1Set unauthenticatedAttributes, TimestampToken timestampToken) { ASN1EncodableVector result = new ASN1EncodableVector(); for (int ii = 0; ii < unauthenticatedAttributes.size(); ii++) { final Attribute attribute = Attribute.getInstance(unauthenticatedAttributes.getObjectAt(ii)); final ASN1ObjectIdentifier attrType = attribute.getAttrType(); if (id_aa_ets_archiveTimestampV2.equals(attrType) || id_aa_ets_archiveTimestampV3.equals(attrType)) { try { TimeStampToken token = new TimeStampToken(new CMSSignedData(DSSASN1Utils .getDEREncoded(attribute.getAttrValues().getObjectAt(0).toASN1Primitive()))); if (!token.getTimeStampInfo().getGenTime().before(timestampToken.getGenerationTime())) { continue; } } catch (Exception e) { throw new DSSException(e); } } result.add(unauthenticatedAttributes.getObjectAt(ii)); } return new DERSequence(result); }
From source file:org.apache.poi.poifs.crypt.dsig.services.TSPTimeStampService.java
License:Apache License
@SuppressWarnings("unchecked") public byte[] timeStamp(byte[] data, RevocationData revocationData) throws Exception { // digest the message MessageDigest messageDigest = CryptoFunctions.getMessageDigest(signatureConfig.getTspDigestAlgo()); byte[] digest = messageDigest.digest(data); // generate the TSP request BigInteger nonce = new BigInteger(128, new SecureRandom()); TimeStampRequestGenerator requestGenerator = new TimeStampRequestGenerator(); requestGenerator.setCertReq(true);// w ww . jav a 2s .c o m String requestPolicy = signatureConfig.getTspRequestPolicy(); if (requestPolicy != null) { requestGenerator.setReqPolicy(new ASN1ObjectIdentifier(requestPolicy)); } ASN1ObjectIdentifier digestAlgoOid = mapDigestAlgoToOID(signatureConfig.getTspDigestAlgo()); TimeStampRequest request = requestGenerator.generate(digestAlgoOid, digest, nonce); byte[] encodedRequest = request.getEncoded(); // create the HTTP POST request Proxy proxy = Proxy.NO_PROXY; if (signatureConfig.getProxyUrl() != null) { URL proxyUrl = new URL(signatureConfig.getProxyUrl()); String host = proxyUrl.getHost(); int port = proxyUrl.getPort(); proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, (port == -1 ? 80 : port))); } HttpURLConnection huc = (HttpURLConnection) new URL(signatureConfig.getTspUrl()).openConnection(proxy); if (signatureConfig.getTspUser() != null) { String userPassword = signatureConfig.getTspUser() + ":" + signatureConfig.getTspPass(); String encoding = DatatypeConverter .printBase64Binary(userPassword.getBytes(Charset.forName("iso-8859-1"))); huc.setRequestProperty("Authorization", "Basic " + encoding); } huc.setRequestMethod("POST"); huc.setConnectTimeout(20000); huc.setReadTimeout(20000); huc.setDoOutput(true); // also sets method to POST. huc.setRequestProperty("User-Agent", signatureConfig.getUserAgent()); huc.setRequestProperty("Content-Type", signatureConfig.isTspOldProtocol() ? "application/timestamp-request" : "application/timestamp-query"); // "; charset=ISO-8859-1"); OutputStream hucOut = huc.getOutputStream(); hucOut.write(encodedRequest); // invoke TSP service huc.connect(); int statusCode = huc.getResponseCode(); if (statusCode != 200) { LOG.log(POILogger.ERROR, "Error contacting TSP server ", signatureConfig.getTspUrl()); throw new IOException("Error contacting TSP server " + signatureConfig.getTspUrl()); } // HTTP input validation String contentType = huc.getHeaderField("Content-Type"); if (null == contentType) { throw new RuntimeException("missing Content-Type header"); } ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(huc.getInputStream(), bos); LOG.log(POILogger.DEBUG, "response content: ", bos.toString()); if (!contentType.startsWith(signatureConfig.isTspOldProtocol() ? "application/timestamp-response" : "application/timestamp-reply")) { throw new RuntimeException("invalid Content-Type: " + contentType); } if (bos.size() == 0) { throw new RuntimeException("Content-Length is zero"); } // TSP response parsing and validation TimeStampResponse timeStampResponse = new TimeStampResponse(bos.toByteArray()); timeStampResponse.validate(request); if (0 != timeStampResponse.getStatus()) { LOG.log(POILogger.DEBUG, "status: " + timeStampResponse.getStatus()); LOG.log(POILogger.DEBUG, "status string: " + timeStampResponse.getStatusString()); PKIFailureInfo failInfo = timeStampResponse.getFailInfo(); if (null != failInfo) { LOG.log(POILogger.DEBUG, "fail info int value: " + failInfo.intValue()); if (/*PKIFailureInfo.unacceptedPolicy*/(1 << 8) == failInfo.intValue()) { LOG.log(POILogger.DEBUG, "unaccepted policy"); } } throw new RuntimeException("timestamp response status != 0: " + timeStampResponse.getStatus()); } TimeStampToken timeStampToken = timeStampResponse.getTimeStampToken(); SignerId signerId = timeStampToken.getSID(); BigInteger signerCertSerialNumber = signerId.getSerialNumber(); X500Name signerCertIssuer = signerId.getIssuer(); LOG.log(POILogger.DEBUG, "signer cert serial number: " + signerCertSerialNumber); LOG.log(POILogger.DEBUG, "signer cert issuer: " + signerCertIssuer); // TSP signer certificates retrieval Collection<X509CertificateHolder> certificates = timeStampToken.getCertificates().getMatches(null); X509CertificateHolder signerCert = null; Map<X500Name, X509CertificateHolder> certificateMap = new HashMap<X500Name, X509CertificateHolder>(); for (X509CertificateHolder certificate : certificates) { if (signerCertIssuer.equals(certificate.getIssuer()) && signerCertSerialNumber.equals(certificate.getSerialNumber())) { signerCert = certificate; } certificateMap.put(certificate.getSubject(), certificate); } // TSP signer cert path building if (signerCert == null) { throw new RuntimeException("TSP response token has no signer certificate"); } List<X509Certificate> tspCertificateChain = new ArrayList<X509Certificate>(); JcaX509CertificateConverter x509converter = new JcaX509CertificateConverter(); x509converter.setProvider("BC"); X509CertificateHolder certificate = signerCert; do { LOG.log(POILogger.DEBUG, "adding to certificate chain: " + certificate.getSubject()); tspCertificateChain.add(x509converter.getCertificate(certificate)); if (certificate.getSubject().equals(certificate.getIssuer())) { break; } certificate = certificateMap.get(certificate.getIssuer()); } while (null != certificate); // verify TSP signer signature X509CertificateHolder holder = new X509CertificateHolder(tspCertificateChain.get(0).getEncoded()); DefaultCMSSignatureAlgorithmNameGenerator nameGen = new DefaultCMSSignatureAlgorithmNameGenerator(); DefaultSignatureAlgorithmIdentifierFinder sigAlgoFinder = new DefaultSignatureAlgorithmIdentifierFinder(); DefaultDigestAlgorithmIdentifierFinder hashAlgoFinder = new DefaultDigestAlgorithmIdentifierFinder(); BcDigestCalculatorProvider calculator = new BcDigestCalculatorProvider(); BcRSASignerInfoVerifierBuilder verifierBuilder = new BcRSASignerInfoVerifierBuilder(nameGen, sigAlgoFinder, hashAlgoFinder, calculator); SignerInformationVerifier verifier = verifierBuilder.build(holder); timeStampToken.validate(verifier); // verify TSP signer certificate if (signatureConfig.getTspValidator() != null) { signatureConfig.getTspValidator().validate(tspCertificateChain, revocationData); } LOG.log(POILogger.DEBUG, "time-stamp token time: " + timeStampToken.getTimeStampInfo().getGenTime()); byte[] timestamp = timeStampToken.getEncoded(); return timestamp; }
From source file:org.demoiselle.signer.timestamp.connector.TimeStampOperator.java
License:Open Source License
/** * Validate a time stamp/*from www . j a va2s .c o m*/ * * @param content if it is assigned, the parameter hash must to be null * @param timeStamp timestamp to be validated * @param hash if it is assigned, the parameter content must to be null * @throws CertificateCoreException validate exception */ @SuppressWarnings("unchecked") public void validate(byte[] content, byte[] timeStamp, byte[] hash) throws CertificateCoreException { try { TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(timeStamp)); CMSSignedData s = timeStampToken.toCMSSignedData(); int verified = 0; Store<?> certStore = s.getCertificates(); SignerInformationStore signers = s.getSignerInfos(); Collection<SignerInformation> c = signers.getSigners(); Iterator<SignerInformation> it = c.iterator(); while (it.hasNext()) { SignerInformation signer = it.next(); Collection<?> certCollection = certStore.getMatches(signer.getSID()); Iterator<?> certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder) certIt.next(); SignerInformationVerifier siv = new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC") .build(cert); if (signer.verify(siv)) { verified++; } cert.getExtension(new ASN1ObjectIdentifier("2.5.29.31")).getExtnValue(); timeStampToken.validate(siv); } logger.info(timeStampMessagesBundle.getString("info.signature.verified", verified)); //Valida o hash incluso no carimbo de tempo com hash do arquivo carimbado byte[] calculatedHash = null; if (content != null) { Digest digest = DigestFactory.getInstance().factoryDefault(); TimeStampTokenInfo info = timeStampToken.getTimeStampInfo(); ASN1ObjectIdentifier algOID = info.getMessageImprintAlgOID(); digest.setAlgorithm(algOID.toString()); calculatedHash = digest.digest(content); } else { calculatedHash = hash; } if (Arrays.equals(calculatedHash, timeStampToken.getTimeStampInfo().getMessageImprintDigest())) { logger.info(timeStampMessagesBundle.getString("info.timestamp.hash.ok")); } else { throw new CertificateCoreException(timeStampMessagesBundle.getString("info.timestamp.hash.nok")); } } catch (TSPException | IOException | CMSException | OperatorCreationException | CertificateException ex) { throw new CertificateCoreException(ex.getMessage()); } }
From source file:org.linagora.linshare.core.service.impl.TimeStampingServiceImpl.java
License:Open Source License
public Date getGenerationTime(TimeStampResponse response) { TimeStampToken tsToken = response.getTimeStampToken(); TimeStampTokenInfo tsInfo = tsToken.getTimeStampInfo(); return tsInfo.getGenTime(); }
From source file:org.signserver.client.cli.defaultimpl.TimeStampCommand.java
License:Open Source License
private void tsaPrintReply() throws Exception { final byte[] bytes = readFiletoBuffer(inrepstring); TimeStampResponse response = null;// ww w . ja v a2 s. c o m out.println("Time-stamp response {"); try { response = new TimeStampResponse(bytes); out.println(" Status: " + response.getStatus()); out.println(" Status message: " + response.getStatusString()); } catch (TSPException ex) { out.println(" Not a response"); } if (response != null) { PKIFailureInfo failureInfo = response.getFailInfo(); if (failureInfo != null) { out.print(" Failure info: "); out.println(failureInfo.intValue()); } } final TimeStampToken token; if (response == null) { token = new TimeStampToken(new CMSSignedData(bytes)); } else { token = response.getTimeStampToken(); } if (token != null) { out.println(" Time-stamp token:"); TimeStampTokenInfo info = token.getTimeStampInfo(); if (info != null) { out.println(" Info:"); out.print(" " + "Accuracy: "); out.println(info.getAccuracy() != null ? info.getAccuracy() : "(null)"); out.print(" " + "Gen Time: "); out.println(info.getGenTime()); out.print(" " + "Gen Time Accuracy: "); out.println(info.getGenTimeAccuracy()); out.print(" " + "Message imprint digest: "); out.println(new String(Hex.encode(info.getMessageImprintDigest()))); out.print(" " + "Message imprint algorithm: "); out.println(info.getMessageImprintAlgOID()); out.print(" " + "Nonce: "); out.println(info.getNonce() != null ? info.getNonce().toString(16) : "(null)"); out.print(" " + "Serial Number: "); out.println(info.getSerialNumber() != null ? info.getSerialNumber().toString(16) : "(null)"); out.print(" " + "TSA: "); out.println(info.getTsa() != null ? info.getTsa() : "(null)"); out.print(" " + "Policy: "); out.println(info.getPolicy()); } out.println(" Signer ID: "); out.println(" Serial Number: " + token.getSID().getSerialNumber().toString(16)); out.println(" Issuer: " + token.getSID().getIssuer()); out.println(" Signer certificate: "); Store certs = token.getCertificates(); Selector signerSelector = new AttributeCertificateHolder(token.getSID().getIssuer(), token.getSID().getSerialNumber()); Collection certCollection = certs.getMatches(signerSelector); for (Object o : certCollection) { if (o instanceof X509CertificateHolder) { X509CertificateHolder cert = (X509CertificateHolder) o; out.println(" Certificate: "); out.println(" Serial Number: " + cert.getSerialNumber().toString(16)); out.println(" Subject: " + cert.getSubject()); out.println(" Issuer: " + cert.getIssuer()); } else { out.println("Not an X.509 certificate: " + o); } } out.println(" Other certificates: "); certCollection = certs.getMatches(new InvertedSelector(signerSelector)); for (Object o : certCollection) { if (o instanceof X509CertificateHolder) { X509CertificateHolder cert = (X509CertificateHolder) o; out.println(" Certificate: "); out.println(" Serial Number: " + cert.getSerialNumber().toString(16)); out.println(" Subject: " + cert.getSubject()); out.println(" Issuer: " + cert.getIssuer()); } else { out.println("Not an X.509 certificate: " + o); } } } out.println("}"); }
From source file:org.signserver.client.cli.defaultimpl.TimeStampCommand.java
License:Open Source License
private void tsaVerify() throws Exception { if (inrepstring == null) { LOG.error("Needs an inrep!"); } else if (signerfilestring == null) { LOG.error("Needs a signerfile!"); } else {//from ww w .j a va 2s . c o m final Collection<X509Certificate> col = getCertsFromPEM(signerfilestring); final X509Certificate[] list = (X509Certificate[]) col.toArray(new X509Certificate[0]); if (list.length == 0) { LOG.error("No certificate found in file: " + signerfilestring); return; } final byte[] b64Bytes = readFiletoBuffer(inrepstring); final byte[] replyBytes = Base64.decode(b64Bytes); final TimeStampResponse timeStampResponse = new TimeStampResponse(replyBytes); final TimeStampToken token = timeStampResponse.getTimeStampToken(); final SignerInformationVerifier infoVerifier = new JcaSimpleSignerInfoVerifierBuilder() .setProvider("BC").build(list[0]); token.validate(infoVerifier); LOG.info("Token was validated successfully."); final TimeStampTokenInfo info = token.getTimeStampInfo(); LOG.info("Token was generated on: " + info.getGenTime()); if (LOG.isDebugEnabled()) { if (info.getMessageImprintAlgOID().equals(TSPAlgorithms.SHA1)) { LOG.debug("Token hash alg: SHA1"); } else { LOG.debug("Token hash alg: " + info.getMessageImprintAlgOID()); } } final byte[] hexDigest = Hex.encode(info.getMessageImprintDigest()); LOG.info("MessageDigest=" + new String(hexDigest)); } }
From source file:org.signserver.module.tsa.TimeStampSigner.java
License:Open Source License
/** * The main method performing the actual timestamp operation. * Expects the signRequest to be a GenericSignRequest contining a * TimeStampRequest// ww w . jav a2 s. co m * * @param signRequest * @param requestContext * @return the sign response * @see org.signserver.server.IProcessable#processData(org.signserver.common.ProcessRequest, org.signserver.common.RequestContext) */ @Override public ProcessResponse processData(final ProcessRequest signRequest, final RequestContext requestContext) throws IllegalRequestException, CryptoTokenOfflineException, SignServerException { // Log values final LogMap logMap = LogMap.getInstance(requestContext); final ISignRequest sReq = (ISignRequest) signRequest; // Check that the request contains a valid TimeStampRequest object. if (!(signRequest instanceof GenericSignRequest)) { final IllegalRequestException exception = new IllegalRequestException( "Recieved request wasn't a expected GenericSignRequest. "); throw exception; } if (!((sReq.getRequestData() instanceof TimeStampRequest) || (sReq.getRequestData() instanceof byte[]))) { final IllegalRequestException exception = new IllegalRequestException( "Recieved request data wasn't a expected TimeStampRequest. "); throw exception; } if (!validChain) { LOG.error("Certificate chain not correctly configured"); throw new CryptoTokenOfflineException("Certificate chain not correctly configured"); } final ITimeSource timeSrc = getTimeSource(); if (LOG.isDebugEnabled()) { LOG.debug("TimeSource: " + timeSrc.getClass().getName()); } final Date date = timeSrc.getGenTime(); final BigInteger serialNumber = getSerialNumber(); // Log values logMap.put(ITimeStampLogger.LOG_TSA_TIME, date == null ? null : String.valueOf(date.getTime())); logMap.put(ITimeStampLogger.LOG_TSA_SERIALNUMBER, serialNumber.toString(16)); logMap.put(ITimeStampLogger.LOG_TSA_TIMESOURCE, timeSrc.getClass().getSimpleName()); GenericSignResponse signResponse = null; ICryptoInstance crypto = null; try { crypto = acquireCryptoInstance(ICryptoToken.PURPOSE_SIGN, signRequest, requestContext); final byte[] requestbytes = (byte[]) sReq.getRequestData(); if (requestbytes == null || requestbytes.length == 0) { LOG.error("Request must contain data"); throw new IllegalRequestException("Request must contain data"); } final TimeStampRequest timeStampRequest = new TimeStampRequest(requestbytes); // Log values for timestamp request logMap.put(ITimeStampLogger.LOG_TSA_TIMESTAMPREQUEST_CERTREQ, String.valueOf(timeStampRequest.getCertReq())); logMap.put(ITimeStampLogger.LOG_TSA_TIMESTAMPREQUEST_CRITEXTOIDS, String.valueOf(timeStampRequest.getCriticalExtensionOIDs())); logMap.put(ITimeStampLogger.LOG_TSA_TIMESTAMPREQUEST_ENCODED, new String(Base64.encode(requestbytes, false))); logMap.put(ITimeStampLogger.LOG_TSA_TIMESTAMPREQUEST_NONCRITEXTOIDS, String.valueOf(timeStampRequest.getNonCriticalExtensionOIDs())); logMap.put(ITimeStampLogger.LOG_TSA_TIMESTAMPREQUEST_NOUNCE, String.valueOf(timeStampRequest.getNonce())); logMap.put(ITimeStampLogger.LOG_TSA_TIMESTAMPREQUEST_VERSION, String.valueOf(timeStampRequest.getVersion())); logMap.put(ITimeStampLogger.LOG_TSA_TIMESTAMPREQUEST_MESSAGEIMPRINTALGOID, timeStampRequest.getMessageImprintAlgOID().getId()); logMap.put(ITimeStampLogger.LOG_TSA_TIMESTAMPREQUEST_MESSAGEIMPRINTDIGEST, new String(Base64.encode(timeStampRequest.getMessageImprintDigest(), false))); final TimeStampTokenGenerator timeStampTokenGen = getTimeStampTokenGenerator(crypto, timeStampRequest, logMap); final TimeStampResponseGenerator timeStampResponseGen = getTimeStampResponseGenerator( timeStampTokenGen); final TimeStampResponse timeStampResponse = timeStampResponseGen.generate(timeStampRequest, serialNumber, date, includeStatusString); final TimeStampToken token = timeStampResponse.getTimeStampToken(); final byte[] signedbytes = timeStampResponse.getEncoded(); // Log values for timestamp response if (LOG.isDebugEnabled()) { LOG.debug("Time stamp response status: " + timeStampResponse.getStatus() + ": " + timeStampResponse.getStatusString()); } logMap.put(ITimeStampLogger.LOG_TSA_PKISTATUS, String.valueOf(timeStampResponse.getStatus())); if (timeStampResponse.getFailInfo() != null) { logMap.put(ITimeStampLogger.LOG_TSA_PKIFAILUREINFO, String.valueOf(timeStampResponse.getFailInfo().intValue())); } logMap.put(ITimeStampLogger.LOG_TSA_TIMESTAMPRESPONSE_ENCODED, new String(Base64.encode(signedbytes, false))); logMap.put(ITimeStampLogger.LOG_TSA_PKISTATUS_STRING, timeStampResponse.getStatusString()); final String archiveId; if (token == null) { archiveId = serialNumber.toString(16); } else { archiveId = token.getTimeStampInfo().getSerialNumber().toString(16); } final Collection<? extends Archivable> archivables = Arrays.asList( new DefaultArchivable(Archivable.TYPE_REQUEST, REQUEST_CONTENT_TYPE, requestbytes, archiveId), new DefaultArchivable(Archivable.TYPE_RESPONSE, RESPONSE_CONTENT_TYPE, signedbytes, archiveId)); if (signRequest instanceof GenericServletRequest) { signResponse = new GenericServletResponse(sReq.getRequestID(), signedbytes, getSigningCertificate(signRequest, requestContext), archiveId, archivables, RESPONSE_CONTENT_TYPE); } else { signResponse = new GenericSignResponse(sReq.getRequestID(), signedbytes, getSigningCertificate(signRequest, requestContext), archiveId, archivables); } // Put in log values if (date == null) { logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, "timeSourceNotAvailable"); } // We were able to fulfill the request so the worker session bean // can go on and charge the client if (timeStampResponse.getStatus() == PKIStatus.GRANTED) { // The client can be charged for the request requestContext.setRequestFulfilledByWorker(true); } else { logMap.put(IWorkerLogger.LOG_PROCESS_SUCCESS, String.valueOf(false)); } } catch (InvalidAlgorithmParameterException e) { final IllegalRequestException exception = new IllegalRequestException( "InvalidAlgorithmParameterException: " + e.getMessage(), e); LOG.error("InvalidAlgorithmParameterException: ", e); logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage()); throw exception; } catch (NoSuchAlgorithmException e) { final IllegalRequestException exception = new IllegalRequestException( "NoSuchAlgorithmException: " + e.getMessage(), e); LOG.error("NoSuchAlgorithmException: ", e); logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage()); throw exception; } catch (NoSuchProviderException e) { final IllegalRequestException exception = new IllegalRequestException( "NoSuchProviderException: " + e.getMessage(), e); LOG.error("NoSuchProviderException: ", e); logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage()); throw exception; } catch (CertStoreException e) { final IllegalRequestException exception = new IllegalRequestException( "CertStoreException: " + e.getMessage(), e); LOG.error("CertStoreException: ", e); logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage()); throw exception; } catch (IOException e) { final IllegalRequestException exception = new IllegalRequestException("IOException: " + e.getMessage(), e); LOG.error("IOException: ", e); logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage()); throw exception; } catch (TSPException e) { final IllegalRequestException exception = new IllegalRequestException(e.getMessage(), e); LOG.error("TSPException: ", e); logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage()); throw exception; } catch (OperatorCreationException e) { final SignServerException exception = new SignServerException(e.getMessage(), e); LOG.error("OperatorCreationException: ", e); logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage()); throw exception; } finally { releaseCryptoInstance(crypto, requestContext); } return signResponse; }
From source file:org.signserver.module.tsa.TimeStampSignerTest.java
License:Open Source License
private int testWithHash(final ASN1ObjectIdentifier hashAlgo) throws Exception { int reqid = random.nextInt(); TimeStampRequestGenerator timeStampRequestGenerator = new TimeStampRequestGenerator(); final TimeStampRequest timeStampRequest = timeStampRequestGenerator.generate(hashAlgo, new byte[getHashLength(hashAlgo)], BigInteger.valueOf(100)); byte[] requestBytes = timeStampRequest.getEncoded(); GenericSignRequest signRequest = new GenericSignRequest(reqid, requestBytes); final GenericSignResponse res = (GenericSignResponse) workerSession.process(WORKER1, signRequest, new RequestContext()); final CertificateFactory factory = CertificateFactory.getInstance("X.509"); final X509Certificate cert = (X509Certificate) factory .generateCertificate(new ByteArrayInputStream(Base64.decode(CERTSTRING.getBytes()))); TimeStampResponse timeStampResponse = null; try {/*from w ww . jav a2 s . c o m*/ // check response timeStampResponse = new TimeStampResponse((byte[]) res.getProcessedData()); timeStampResponse.validate(timeStampRequest); if (timeStampResponse.getStatus() != PKIStatus.GRANTED) { // return early and don't attempt to get a token return timeStampResponse.getStatus(); } // check the hash value from the response TimeStampToken token = timeStampResponse.getTimeStampToken(); AlgorithmIdentifier algo = token.getTimeStampInfo().getHashAlgorithm(); assertEquals("Timestamp response is using incorrect hash algorithm", hashAlgo, algo.getAlgorithm()); Collection signerInfos = token.toCMSSignedData().getSignerInfos().getSigners(); // there should be one SignerInfo assertEquals("There should only be one signer in the timestamp response", 1, signerInfos.size()); for (Object o : signerInfos) { SignerInformation si = (SignerInformation) o; // test the response signature algorithm assertEquals("Timestamp used unexpected signature algorithm", TSPAlgorithms.SHA1.toString(), si.getDigestAlgOID()); assertEquals("Timestamp is signed with unexpected signature encryption algorithm", "1.2.840.113549.1.1.1", si.getEncryptionAlgOID()); final AttributeTable attrs = si.getSignedAttributes(); final ASN1EncodableVector scAttrs = attrs.getAll(PKCSObjectIdentifiers.id_aa_signingCertificate); assertEquals("Should contain a signingCertificate signed attribute", 1, scAttrs.size()); TestUtils.checkSigningCertificateAttribute(ASN1Sequence.getInstance(scAttrs.get(0)), cert); } } catch (TSPException e) { fail("Failed to verify response"); } catch (IOException e) { fail("Failed to verify response"); } final TimeStampToken token = timeStampResponse.getTimeStampToken(); try { token.validate(cert, "BC"); } catch (TSPException e) { fail("Failed to validate response token"); } return timeStampResponse.getStatus(); }
From source file:org.signserver.module.xades.signer.InternalTimeStampTokenProvider.java
License:Open Source License
@Override public TimeStampTokenRes getTimeStampToken(final byte[] tsDigestInput, final String digestAlgUri) throws TimeStampTokenGenerationException { try {// w w w .j a va 2 s .c o m MessageDigest md = messageDigestProvider.getEngine(digestAlgUri); byte[] imprint = md.digest(tsDigestInput); TimeStampToken token = fetcher.fetchToken(imprint, digestUriToOidMap.get(digestAlgUri)); return new TimeStampTokenRes(token.getEncoded(), token.getTimeStampInfo().getGenTime()); } catch (UnsupportedAlgorithmException ex) { throw new TimeStampTokenGenerationException("Digest algorithm not supported", ex); } catch (IllegalRequestException ex) { throw new TimeStampTokenGenerationException("The time-stamp request failed", ex); } catch (CryptoTokenOfflineException ex) { throw new TimeStampTokenGenerationException( "The time-stamp request could not be processed because of offline TSA", ex); } catch (SignServerException ex) { throw new TimeStampTokenGenerationException( "The time-stamp request could not be processed because of internal error in the TSA", ex); } catch (TSPException ex) { throw new TimeStampTokenGenerationException("Invalid time stamp response", ex); } catch (IOException ex) { throw new TimeStampTokenGenerationException("Encoding error", ex); } }
From source file:org.votingsystem.signature.smime.SMIMEMessage.java
License:Open Source License
public void setTimeStampToken(TimeStampToken timeStampToken) throws Exception { if (timeStampToken == null) throw new Exception("timestamp token null"); DERObject derObject = new ASN1InputStream(timeStampToken.getEncoded()).readObject(); DERSet derset = new DERSet(derObject); Attribute timeStampAsAttribute = new Attribute(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken, derset); Hashtable hashTable = new Hashtable(); hashTable.put(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken, timeStampAsAttribute); AttributeTable timeStampAsAttributeTable = new AttributeTable(hashTable); byte[] timeStampTokenHash = timeStampToken.getTimeStampInfo().getMessageImprintDigest(); Iterator<SignerInformation> it = smimeSigned.getSignerInfos().getSigners().iterator(); List<SignerInformation> newSigners = new ArrayList<SignerInformation>(); while (it.hasNext()) { SignerInformation signer = it.next(); byte[] digestBytes = CMSUtils.getSignerDigest(signer); if (Arrays.equals(timeStampTokenHash, digestBytes)) { log.info("setTimeStampToken - found signer"); AttributeTable attributeTable = signer.getUnsignedAttributes(); SignerInformation updatedSigner = null; if (attributeTable != null) { log.info("setTimeStampToken - signer with UnsignedAttributes"); hashTable = attributeTable.toHashtable(); hashTable.put(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken, timeStampAsAttribute); timeStampAsAttributeTable = new AttributeTable(hashTable); }/*w w w . ja v a2 s . c o m*/ updatedSigner = signer.replaceUnsignedAttributes(signer, timeStampAsAttributeTable); newSigners.add(updatedSigner); } else newSigners.add(signer); } SignerInformationStore newSignersStore = new SignerInformationStore(newSigners); CMSSignedData cmsdata = smimeSigned.replaceSigners(smimeSigned, newSignersStore); replaceSigners(cmsdata); }