private void badAlgorithmTest(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs) { TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( privateKey, cert, TspAlgorithms.Sha1, "1.2"); tsTokenGen.SetCertificates(certs); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); TimeStampRequest request = reqGen.Generate(new DerObjectIdentifier("1.2.3.4.5"), new byte[21]); TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed); TimeStampResponse tsResp = tsRespGen.Generate(request, BigInteger.ValueOf(23), DateTime.UtcNow); tsResp = new TimeStampResponse(tsResp.GetEncoded()); TimeStampToken tsToken = tsResp.TimeStampToken; if (tsToken != null) { Assert.Fail("badAlgorithm - token not null."); } PkiFailureInfo failInfo = tsResp.GetFailInfo(); if (failInfo == null) { Assert.Fail("badAlgorithm - failInfo set to null."); } if (failInfo.IntValue != PkiFailureInfo.BadAlg) { Assert.Fail("badAlgorithm - wrong failure info returned."); } }
private void incorrectHashTest(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs) { TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( privateKey, cert, TspAlgorithms.Sha1, "1.2"); tsTokenGen.SetCertificates(certs); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha1, new byte[16]); TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed); TimeStampResponse tsResp = tsRespGen.Generate(request, BigInteger.ValueOf(23), DateTime.UtcNow); tsResp = new TimeStampResponse(tsResp.GetEncoded()); TimeStampToken tsToken = tsResp.TimeStampToken; Assert.IsNull(tsToken, "incorrect hash -- token not null"); PkiFailureInfo failInfo = tsResp.GetFailInfo(); if (failInfo == null) { Assert.Fail("incorrectHash - failInfo set to null."); } if (failInfo.IntValue != PkiFailureInfo.BadDataFormat) { Assert.Fail("incorrectHash - wrong failure info returned."); } }
public void TestBadAlgorithm() { TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( privateKey, cert, TspAlgorithms.Sha1, "1.2"); tsTokenGen.SetCertificates(certs); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); TimeStampRequest request = reqGen.Generate("1.2.3.4.5", new byte[20]); TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed); TimeStampResponse tsResp = tsRespGen.Generate(request, BigInteger.ValueOf(23), DateTime.UtcNow); tsResp = new TimeStampResponse(tsResp.GetEncoded()); TimeStampToken tsToken = tsResp.TimeStampToken; if (tsToken != null) { Assert.Fail("badAlgorithm - token not null."); } PkiFailureInfo failInfo = tsResp.GetFailInfo(); if (failInfo == null) { Assert.Fail("badAlgorithm - failInfo set to null."); } if (failInfo.IntValue != PkiFailureInfo.BadAlg) { Assert.Fail("badAlgorithm - wrong failure info returned."); } }
private void tokenEncodingTest(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs) { TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( privateKey, cert, TspAlgorithms.Sha1, "1.2.3.4.5.6"); tsTokenGen.SetCertificates(certs); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20], BigInteger.ValueOf(100)); TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed); TimeStampResponse tsResp = tsRespGen.Generate(request, BigInteger.ValueOf(23), DateTime.UtcNow); tsResp = new TimeStampResponse(tsResp.GetEncoded()); TimeStampResponse tsResponse = new TimeStampResponse(tsResp.GetEncoded()); if (!Arrays.AreEqual(tsResponse.GetEncoded(), tsResp.GetEncoded()) || !Arrays.AreEqual(tsResponse.TimeStampToken.GetEncoded(), tsResp.TimeStampToken.GetEncoded())) { Assert.Fail(); } }
/// <summary> /// Gets a time-stamp of the provided address via the RFC3161. /// </summary> /// <param name="hash">The has to get the time-stamp from</param> /// <param name="digestMethod">The algorithm used to calculate the hash</param> /// <returns>The time-stamp token in binary (encoded) format</returns> /// <exception cref="WebException">When the TSA returned a http-error</exception> /// <exception cref="TspValidationException">When the TSA returns an invalid time-stamp response</exception> public async Task <byte[]> GetTimestampFromDocumentHashAsync(byte[] hash, string digestMethod) { TimeStampRequest tspReq = CreateRfc3161RequestBody(hash, digestMethod); Stream postStream; byte[] tsprBytes = tspReq.GetEncoded(); HttpWebRequest post = CreateRfc3161WebRequest(tsprBytes, out postStream); trace.TraceEvent(TraceEventType.Information, 0, "retrieving time-stamp of {0} from {1}", Convert.ToBase64String(hash), address); await postStream.WriteAsync(tsprBytes, 0, tsprBytes.Length); using (var response = (HttpWebResponse)post.GetResponse()) { MemoryStream rspStream = new MemoryStream(); Task rspCopy = response.GetResponseStream().CopyToAsync(rspStream); CheckRfc3161WebResponse(response); await rspCopy; return(ParseRfc3161ResponseBody(rspStream.ToArray(), tspReq)); } }
private TimeStampResponse GetTimeStampResponse(TimeStampRequest request) { List <Exception> exceptions = new List <Exception>(); /* Try primary TSA */ try { HttpWebRequest httpRequest = CreateHttpRequest(this.tsaPrimaryUrl, this.tsaPrimaryCredentials); Stream requestStream = httpRequest.GetRequestStream(); requestStream.Write(request.GetEncoded(), 0, request.GetEncoded().Length); return(new TimeStampResponse(httpRequest.GetResponse().GetResponseStream())); } catch (Exception e) { if (String.IsNullOrWhiteSpace(this.tsaSecondaryUrl)) { throw new TimestampException("Cannot connect to primary TSA server", e); } exceptions.Add(e); } /* Try secondary TSA */ try { HttpWebRequest httpRequest = CreateHttpRequest(this.tsaSecondaryUrl, this.tsaSecondaryCredentials); Stream requestStream = httpRequest.GetRequestStream(); requestStream.Write(request.GetEncoded(), 0, request.GetEncoded().Length); return(new TimeStampResponse(httpRequest.GetResponse().GetResponseStream())); } catch (Exception e) { exceptions.Add(e); throw new AggregateException("Cannot connect to primary or secondary TSA server", exceptions); } }
/// <summary> /// verifica implicitamente la marca a partire dalle sole informazioni contenute nel file TSR /// </summary> /// <param name="fileTSR"></param> /// <returns></returns> public OutputResponseMarca Verify(byte[] fileTSR) { TimeStampRequest tsReq = null; TimeStampResponse tsRes = null; if (fileTSR.Length > 0) { tsRes = getTsRes(fileTSR); } else { logger.Debug("File TSR mancante oppure corrotto!"); return(null); } TimeStampRequestGenerator tsqGen = new TimeStampRequestGenerator(); //quando impostato a true significa che nella risposta della TSA deve essere incluso il certificato della firma tsqGen.SetCertReq(true); //fra i parametri non metto il Nonce perchè questa è una verifica off-line!!! byte[] fileHash = tsRes.TimeStampToken.TimeStampInfo.TstInfo.MessageImprint.GetHashedMessage(); tsReq = tsqGen.Generate(TspAlgorithms.Sha256, fileHash); return(checkMarca(tsRes, tsReq)); }
public TimeStampResponse GetTimeStampResponse(string digestAlgorithmOid, byte[] digest) { TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator(); tsqGenerator.SetCertReq(true); // tsqGenerator.setReqPolicy("1.3.6.1.4.1.601.10.3.1"); BigInteger nonce = BigInteger.ValueOf(DateTime.Now.Ticks + Environment.TickCount); TimeStampRequest request = tsqGenerator.Generate(digestAlgorithmOid, digest, nonce); TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator(keyPair.Private, cert, TspAlgorithms.Sha256, "1.2"); var certs = new ArrayList { cert }; var certStore = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(certs)); tsTokenGen.SetCertificates(certStore); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); //TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20], BigInteger.ValueOf(100)); TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed); TimeStampResponse tsResp = tsRespGen.Generate(request, BigInteger.ValueOf(23), DateTime.UtcNow); tsResp = new TimeStampResponse(tsResp.GetEncoded()); return(tsResp); }
/// <summary> /// /// </summary> /// <param name="filep7m"></param> /// <param name="fileTSR"></param> /// <returns></returns> public OutputResponseMarca Verify(byte[] filep7m, byte[] fileTSR) { TimeStampRequest tsReq = null; TimeStampResponse tsRes = null; if (fileTSR.Length > 0) { tsRes = getTsRes(fileTSR); } else { logger.Debug("File TSR mancante oppure corrotto!"); return(null); } DerObjectIdentifier algoOid = tsRes.TimeStampToken.TimeStampInfo.HashAlgorithm.ObjectID; if (filep7m.Length > 0) { tsReq = getTsReq(filep7m, algoOid); } else { logger.Debug("File p7m mancante oppure corrotto!"); return(null); } return(checkMarca(tsRes, tsReq)); }
private void basicTestWithTSA(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs) { TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( privateKey, cert, TspAlgorithms.Sha1, "1.2"); tsTokenGen.SetCertificates(certs); tsTokenGen.SetTsa(new Asn1.X509.GeneralName(new X509Name("CN=Test"))); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20], BigInteger.ValueOf(100)); TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed); TimeStampResponse tsResp = tsRespGen.Generate(request, BigInteger.ValueOf(23), DateTime.UtcNow); tsResp = new TimeStampResponse(tsResp.GetEncoded()); TimeStampToken tsToken = tsResp.TimeStampToken; tsToken.Validate(cert); Asn1.Cms.AttributeTable table = tsToken.SignedAttributes; Assert.IsNotNull(table[PkcsObjectIdentifiers.IdAASigningCertificate], "no signingCertificate attribute found"); }
private TimeStampResponse getTimeStamp(string URL) { //RFC3161 compliant Time Stamp Authority (TSA) server TimeStampResponse response = null; byte[] sha1Digest = new byte [20]; TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); //SecureRandom randomGenerator = SecureRandom.GetInstance("SHA1PRNG"); //long nonce = randomGenerator.NextLong(); Org.BouncyCastle.Asn1.DerObjectIdentifier oDR = new Org.BouncyCastle.Asn1.DerObjectIdentifier("1.3.6.1.4.1.311.3.2.1"); // request with digestAlgorithmOID, byte[] digest, java.math.BigInteger nonc //byte[] digest = TSToken.TimeStampInfo.GetMessageImprintDigest(); TimeStampRequest request = reqGen.Generate(oDR, sha1Digest, Org.BouncyCastle.Math.BigInteger.ValueOf(100)); byte[] reqData = request.GetEncoded(); WebRequest conn = WebRequest.Create(URL); Stream st = conn.GetRequestStream(); st.Write(reqData, 0, reqData.Length); st.Flush(); st.Close(); var resposta = conn.GetResponse(); Stream stReponse = resposta.GetResponseStream(); response = new TimeStampResponse(stReponse); stReponse.Close(); return(response); }
public void TestAccuracyZeroCerts() { TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( privateKey, cert, TspAlgorithms.MD5, "1.2"); tsTokenGen.SetCertificates(certs); tsTokenGen.SetAccuracySeconds(1); tsTokenGen.SetAccuracyMillis(2); tsTokenGen.SetAccuracyMicros(3); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20], BigInteger.ValueOf(100)); TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed); TimeStampResponse tsResp = tsRespGen.Generate(request, BigInteger.ValueOf(23), DateTime.UtcNow); tsResp = new TimeStampResponse(tsResp.GetEncoded()); TimeStampToken tsToken = tsResp.TimeStampToken; tsToken.Validate(cert); // // check validation // tsResp.Validate(request); // // check tstInfo // TimeStampTokenInfo tstInfo = tsToken.TimeStampInfo; // // check accuracy // GenTimeAccuracy accuracy = tstInfo.GenTimeAccuracy; Assert.AreEqual(1, accuracy.Seconds); Assert.AreEqual(2, accuracy.Millis); Assert.AreEqual(3, accuracy.Micros); Assert.AreEqual(BigInteger.ValueOf(23), tstInfo.SerialNumber); Assert.AreEqual("1.2", tstInfo.Policy); // // test certReq // IX509Store store = tsToken.GetCertificates("Collection"); ICollection certificates = store.GetMatches(null); Assert.AreEqual(0, certificates.Count); }
public void TestNoNonce() { TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( privateKey, cert, TspAlgorithms.MD5, "1.2.3"); tsTokenGen.SetCertificates(certs); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20]); Assert.IsFalse(request.CertReq); TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed); TimeStampResponse tsResp = tsRespGen.Generate(request, BigInteger.ValueOf(24), DateTime.UtcNow); tsResp = new TimeStampResponse(tsResp.GetEncoded()); TimeStampToken tsToken = tsResp.TimeStampToken; tsToken.Validate(cert); // // check validation // tsResp.Validate(request); // // check tstInfo // TimeStampTokenInfo tstInfo = tsToken.TimeStampInfo; // // check accuracy // GenTimeAccuracy accuracy = tstInfo.GenTimeAccuracy; Assert.IsNull(accuracy); Assert.AreEqual(BigInteger.ValueOf(24), tstInfo.SerialNumber); Assert.AreEqual("1.2.3", tstInfo.Policy); Assert.IsFalse(tstInfo.IsOrdered); Assert.IsNull(tstInfo.Nonce); // // test certReq // IX509Store store = tsToken.GetCertificates("Collection"); ICollection certificates = store.GetMatches(null); Assert.AreEqual(0, certificates.Count); }
/** * Get RFC 3161 timeStampToken. * Method may return null indicating that timestamp should be skipped. * @param imprint data imprint to be time-stamped * @return encoded, TSA signed data of the timeStampToken */ public virtual byte[] GetTimeStampToken(byte[] imprint) { byte[] respBytes = null; // Setup the time stamp request TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator(); tsqGenerator.SetCertReq(true); if (!string.IsNullOrEmpty(tsaReqPolicy)) { tsqGenerator.SetReqPolicy(tsaReqPolicy); } // tsqGenerator.setReqPolicy("1.3.6.1.4.1.601.10.3.1"); BigInteger nonce = BigInteger.ValueOf(DateTime.Now.Ticks + Environment.TickCount); TimeStampRequest request = tsqGenerator.Generate(DigestAlgorithms.GetAllowedDigests(digestAlgorithm), imprint, nonce); byte[] requestBytes = request.GetEncoded(); // Call the communications layer respBytes = GetTSAResponse(requestBytes); // Handle the TSA response TimeStampResponse response = new TimeStampResponse(respBytes); // validate communication level attributes (RFC 3161 PKIStatus) response.Validate(request); PkiFailureInfo failure = response.GetFailInfo(); int value = (failure == null) ? 0 : failure.IntValue; if (value != 0) { // @todo: Translate value of 15 error codes defined by PKIFailureInfo to string throw new IOException(MessageLocalization.GetComposedMessage("invalid.tsa.1.response.code.2", tsaURL, value)); } // @todo: validate the time stap certificate chain (if we want // assure we do not sign using an invalid timestamp). // extract just the time stamp token (removes communication status info) TimeStampToken tsToken = response.TimeStampToken; if (tsToken == null) { throw new IOException(MessageLocalization.GetComposedMessage("tsa.1.failed.to.return.time.stamp.token.2", tsaURL, response.GetStatusString())); } TimeStampTokenInfo tsTokenInfo = tsToken.TimeStampInfo; // to view details byte[] encoded = tsToken.GetEncoded(); LOGGER.Info("Timestamp generated: " + tsTokenInfo.GenTime); if (tsaInfo != null) { tsaInfo.InspectTimeStampTokenInfo(tsTokenInfo); } // Update our token size estimate for the next call (padded to be safe) this.tokenSizeEstimate = encoded.Length + 32; return(encoded); }
public override void Respond(HttpListenerContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (!string.Equals(context.Request.ContentType, RequestContentType, StringComparison.OrdinalIgnoreCase)) { context.Response.StatusCode = 400; return; } var bytes = ReadRequestBody(context.Request); var request = new TimeStampRequest(bytes); var tokenGenerator = new TimeStampTokenGenerator( _keyPair.Private, Certificate, _options.SignatureHashAlgorithm.Value, _options.Policy.Value); if (_options.ReturnSigningCertificate) { var certificates = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(new[] { Certificate })); tokenGenerator.SetCertificates(certificates); } SetAccuracy(tokenGenerator); var responseGenerator = new TimeStampResponseGenerator(tokenGenerator, TspAlgorithms.Allowed); TimeStampResponse response; if (_options.ReturnFailure) { response = responseGenerator.GenerateFailResponse( PkiStatus.Rejection, PkiFailureInfo.BadAlg, "Unsupported algorithm"); } else { response = responseGenerator.Generate(request, _nextSerialNumber, DateTime.UtcNow); } _serialNumbers.Add(_nextSerialNumber); _nextSerialNumber = _nextSerialNumber.Add(BigInteger.One); context.Response.ContentType = ResponseContentType; WriteResponseBody(context.Response, response.GetEncoded()); }
/// <summary>Get RFC 3161 timeStampToken.</summary> /// <remarks> /// Get RFC 3161 timeStampToken. /// Method may return null indicating that timestamp should be skipped. /// </remarks> /// <param name="imprint">data imprint to be time-stamped</param> /// <returns>encoded, TSA signed data of the timeStampToken</returns> /// <exception cref="System.IO.IOException"/> /// <exception cref="Org.BouncyCastle.Tsp.TSPException"/> public virtual byte[] GetTimeStampToken(byte[] imprint) { byte[] respBytes = null; // Setup the time stamp request TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator(); tsqGenerator.SetCertReq(true); if (tsaReqPolicy != null && tsaReqPolicy.Length > 0) { tsqGenerator.SetReqPolicy(tsaReqPolicy); } // tsqGenerator.setReqPolicy("1.3.6.1.4.1.601.10.3.1"); BigInteger nonce = BigInteger.ValueOf(SystemUtil.GetTimeBasedSeed()); TimeStampRequest request = tsqGenerator.Generate(new DerObjectIdentifier(DigestAlgorithms.GetAllowedDigest (digestAlgorithm)), imprint, nonce); byte[] requestBytes = request.GetEncoded(); // Call the communications layer respBytes = GetTSAResponse(requestBytes); // Handle the TSA response TimeStampResponse response = new TimeStampResponse(respBytes); // validate communication level attributes (RFC 3161 PKIStatus) response.Validate(request); PkiFailureInfo failure = response.GetFailInfo(); int value = (failure == null) ? 0 : failure.IntValue; if (value != 0) { // @todo: Translate value of 15 error codes defined by PKIFailureInfo to string throw new PdfException(PdfException.InvalidTsa1ResponseCode2).SetMessageParams(tsaURL, value.ToString()); } // @todo: validate the time stap certificate chain (if we want // assure we do not sign using an invalid timestamp). // extract just the time stamp token (removes communication status info) TimeStampToken tsToken = response.TimeStampToken; if (tsToken == null) { throw new PdfException(PdfException.Tsa1FailedToReturnTimeStampToken2).SetMessageParams(tsaURL, response.GetStatusString ()); } TimeStampTokenInfo tsTokenInfo = tsToken.TimeStampInfo; // to view details byte[] encoded = tsToken.GetEncoded(); LOGGER.Info("Timestamp generated: " + tsTokenInfo.GenTime); if (tsaInfo != null) { tsaInfo.InspectTimeStampTokenInfo(tsTokenInfo); } // Update our token size estimate for the next call (padded to be safe) this.tokenSizeEstimate = encoded.Length + 32; return(encoded); }
private void testNoNonse(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs) { TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( privateKey, cert, TspAlgorithms.MD5, "1.2.3"); tsTokenGen.SetCertificates(certs); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20]); ArrayList algorithms = new ArrayList(); algorithms.Add(TspAlgorithms.Sha1); request.Validate(algorithms, new ArrayList(), new ArrayList()); Assert.False(request.CertReq); TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed); TimeStampResponse tsResp = tsRespGen.Generate(request, new BigInteger("24"), DateTime.UtcNow); tsResp = new TimeStampResponse(tsResp.GetEncoded()); TimeStampToken tsToken = tsResp.TimeStampToken; tsToken.Validate(cert); tsResp.Validate(request); TimeStampTokenInfo tstInfo = tsToken.TimeStampInfo; GenTimeAccuracy accuracy = tstInfo.GenTimeAccuracy; Assert.IsNull(accuracy); Assert.IsTrue(new BigInteger("24").Equals(tstInfo.SerialNumber)); Assert.IsTrue("1.2.3" == tstInfo.Policy); Assert.False(tstInfo.IsOrdered); Assert.IsNull(tstInfo.Nonce); // // test certReq // IX509Store store = tsToken.GetCertificates(); ICollection certificates = store.GetMatches(null); Assert.IsTrue(0 == certificates.Count); }
public void TestNullPolicy() { // null in request and token generator - should fail TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( privateKey, cert, TspAlgorithms.Sha1, null); tsTokenGen.SetCertificates(certs); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20]); TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed, null); TimeStampResponse tsResp = tsRespGen.Generate(request, BigInteger.ValueOf(23), DateTime.UtcNow); tsResp = new TimeStampResponse(tsResp.GetEncoded()); TimeStampToken tsToken = tsResp.TimeStampToken; if (tsToken != null) { Assert.Fail("badPolicy - token not null."); } PkiFailureInfo failInfo = tsResp.GetFailInfo(); if (failInfo == null) { Assert.Fail("badPolicy - failInfo set to null."); } if (failInfo.IntValue != PkiFailureInfo.UnacceptedPolicy) { Assert.Fail("badPolicy - wrong failure info returned."); } // request specifies policy, token generator doesn't - should work reqGen = new TimeStampRequestGenerator(); reqGen.SetReqPolicy("1.1"); request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20]); tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed, null); tsResp = tsRespGen.Generate(request, BigInteger.ValueOf(24), DateTime.UtcNow); tsResp = new TimeStampResponse(tsResp.GetEncoded()); tsToken = tsResp.TimeStampToken; Assert.AreEqual(tsToken.TimeStampInfo.Policy, "1.1"); // policy should be picked up off request }
/// <exception cref="System.Exception"/> public virtual byte[] GetTimeStampToken(byte[] imprint) { TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator(); tsqGenerator.SetCertReq(true); BigInteger nonce = BigInteger.ValueOf(SystemUtil.GetTimeBasedSeed()); TimeStampRequest request = tsqGenerator.Generate(new DerObjectIdentifier(DigestAlgorithms.GetAllowedDigest (DIGEST_ALG)), imprint, nonce); return(new TestTimestampTokenBuilder(tsaCertificateChain, tsaPrivateKey).CreateTimeStampToken(request)); }
private void testAccuracyWithCertsAndOrdering(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs) { TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( privateKey, cert, TspAlgorithms.MD5, "1.2.3"); tsTokenGen.SetCertificates(certs); tsTokenGen.SetAccuracySeconds(1); tsTokenGen.SetAccuracyMillis(2); tsTokenGen.SetAccuracyMicros(3); tsTokenGen.SetOrdering(true); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); reqGen.SetCertReq(true); TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20], BigInteger.ValueOf(100)); TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed); // // This is different to the Java API. // TimeStampResponse tsResp = tsRespGen.Generate(request, BigInteger.ValueOf(23), DateTime.UtcNow); tsResp = new TimeStampResponse(tsResp.GetEncoded()); TimeStampToken tsToken = tsResp.TimeStampToken; tsResp.Validate(request); TimeStampTokenInfo tstInfo = tsToken.TimeStampInfo; GenTimeAccuracy accuracy = tstInfo.GenTimeAccuracy; Assert.IsTrue(1 == accuracy.Seconds); Assert.IsTrue(2 == accuracy.Millis); Assert.IsTrue(3 == accuracy.Micros); Assert.IsTrue(new BigInteger("23").Equals(tstInfo.SerialNumber)); Assert.IsTrue("1.2.3" == tstInfo.Policy); IX509Store store = tsToken.GetCertificates(); ICollection certificates = store.GetMatches(null); Assert.IsTrue(2 == certificates.Count); }
/// <summary> /// Initializes a new instance of the <see cref="Request"/> class. /// </summary> /// <param name="tsrBytes">DER encoded time stamp request</param> public Request(byte[] tsrBytes) { TimeStampRequest req; req = new TimeStampRequest(tsrBytes); byte[] nonce = null; if (null != req.Nonce) { nonce = req.Nonce.ToByteArray(); } this.Setup(req.GetMessageImprintDigest(), req.MessageImprintAlgOid, nonce, req.ReqPolicy, req.CertReq, req.Version); }
/// <summary> /// Realiza la petición de sellado del hash que se pasa como parametro y devuelve la /// respuesta del servidor. /// </summary> /// <param name="hash"></param> /// <param name="digestMethod"></param> /// <param name="certReq"></param> /// <returns></returns> public byte[] GetTimeStamp(byte[] hash, DigestMethod digestMethod, bool certReq) { TimeStampRequestGenerator tsrq = new TimeStampRequestGenerator(); tsrq.SetCertReq(certReq); BigInteger nonce = BigInteger.ValueOf(DateTime.Now.Ticks); TimeStampRequest tsr = tsrq.Generate(digestMethod.Oid, hash, nonce); byte[] data = tsr.GetEncoded(); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(_url); req.Method = "POST"; req.ContentType = "application/timestamp-query"; req.ContentLength = data.Length; if (!string.IsNullOrEmpty(_user) && !string.IsNullOrEmpty(_password)) { string auth = string.Format("{0}:{1}", _user, _password); req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(auth), Base64FormattingOptions.None); } Stream reqStream = req.GetRequestStream(); reqStream.Write(data, 0, data.Length); reqStream.Close(); HttpWebResponse res = (HttpWebResponse)req.GetResponse(); if (res.StatusCode != HttpStatusCode.OK) { throw new Exception("El servidor ha devuelto una respuesta no válida"); } else { Stream resStream = new BufferedStream(res.GetResponseStream()); TimeStampResponse tsRes = new TimeStampResponse(resStream); resStream.Close(); tsRes.Validate(tsr); if (tsRes.TimeStampToken == null) { throw new Exception("El servidor no ha devuelto ningún sello de tiempo"); } return(tsRes.TimeStampToken.GetEncoded()); } }
public override void Respond(HttpListenerContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (!string.Equals(context.Request.ContentType, RequestContentType, StringComparison.OrdinalIgnoreCase)) { context.Response.StatusCode = 400; return; } var bytes = ReadRequestBody(context.Request); var request = new TimeStampRequest(bytes); PkiStatusInfo statusInfo; BcContentInfo timeStampToken = null; if (_options.ReturnFailure) { statusInfo = new PkiStatusInfo( (int)PkiStatus.Rejection, new PkiFreeText(new DerUtf8String("Unsupported algorithm")), new PkiFailureInfo(PkiFailureInfo.BadAlg)); } else { statusInfo = new PkiStatusInfo((int)PkiStatus.Granted); var generalizedTime = DateTime.UtcNow; if (_options.GeneralizedTime.HasValue) { generalizedTime = _options.GeneralizedTime.Value.UtcDateTime; } CmsSignedData timestamp = GenerateTimestamp(request, _nextSerialNumber, generalizedTime); timeStampToken = timestamp.ContentInfo; } _serialNumbers.Add(_nextSerialNumber); _nextSerialNumber = _nextSerialNumber.Add(BigInteger.One); context.Response.ContentType = ResponseContentType; var response = new TimeStampResp(statusInfo, timeStampToken); WriteResponseBody(context.Response, response.GetEncoded()); }
/// <summary> /// Realiza la petición de sellado del hash que se pasa como parametro y devuelve la /// respuesta del servidor. /// </summary> /// <param name="url"></param> /// <param name="hash"></param> /// <param name="digestMethod"></param> /// <param name="certReq"></param> /// <returns></returns> public static byte[] GetTimeStamp(string url, byte[] hash, DigestMethod digestMethod, bool certReq) { string digestAlg; TimeStampRequestGenerator tsrq = new TimeStampRequestGenerator(); tsrq.SetCertReq(certReq); if (digestMethod == DigestMethod.SHA1) { digestAlg = TspAlgorithms.Sha1; } else if (digestMethod == DigestMethod.SHA256) { digestAlg = TspAlgorithms.Sha256; } else { digestAlg = TspAlgorithms.Sha512; } TimeStampRequest tsr = tsrq.Generate(digestAlg, hash, BigInteger.ValueOf(100)); byte[] data = tsr.GetEncoded(); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.Method = "POST"; req.ContentType = "application/timestamp-query"; req.ContentLength = data.Length; Stream reqStream = req.GetRequestStream(); reqStream.Write(data, 0, data.Length); reqStream.Close(); HttpWebResponse res = (HttpWebResponse)req.GetResponse(); if (res == null) { return(null); } else { Stream resStream = new BufferedStream(res.GetResponseStream()); TimeStampResponse tsRes = new TimeStampResponse(resStream); resStream.Close(); return(tsRes.TimeStampToken.GetEncoded()); } }
/// <summary> /// Saves an audit register of the operation /// </summary> /// <param name="timeStampRequest"><see cref="TimeStampRequest"/></param> /// <param name="timeStampToken"><see cref="TimeStampToken"/></param> /// <param name="tsaCertificate"><see cref="X509Certificate"/></param> /// <returns></returns> private Task SaveAuditLog(TimeStampRequest timeStampRequest, TimeStampToken timeStampToken, X509Certificate tsaCertificate) { var audit = new TimeStampAudit { HashAlgorithm = timeStampRequest.MessageImprintAlgOid, HashMessage = timeStampRequest.GetMessageImprintDigest(), Policy = BcTimeStampResponderRepository.GetPolicyOid(), Serial = timeStampToken.TimeStampInfo.SerialNumber.ToString(), SignedTime = timeStampToken.TimeStampInfo.GenTime, TsaSerial = tsaCertificate.SerialNumber.ToString() }; return(BcTimeStampResponderRepository.SaveAuditLog(audit)); }
private static void responseParse( byte[] request, byte[] response, string algorithm) { TimeStampRequest req = new TimeStampRequest(request); TimeStampResponse resp = new TimeStampResponse(response); resp.Validate(req); X509Certificate cert = new X509CertificateParser().ReadCertificate(signingCert); resp.TimeStampToken.Validate(cert); }
private bool TestaTimeStamp(string URL) { SHA1 sha1 = SHA1CryptoServiceProvider.Create(); byte[] hash = sha1.ComputeHash(Encoding.ASCII.GetBytes("TESTE DE SELO")); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); reqGen.SetCertReq(true); TimeStampRequest tsReq = reqGen.Generate(TspAlgorithms.Sha1, hash, BigInteger.ValueOf(100)); byte[] tsData = tsReq.GetEncoded(); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URL); req.Method = "POST"; req.ContentType = "application/timestamp-query"; req.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes("9024:"))); req.ContentLength = tsData.Length; Stream reqStream = req.GetRequestStream(); reqStream.Write(tsData, 0, tsData.Length); reqStream.Close(); HttpWebResponse res = (HttpWebResponse)req.GetResponse(); if (res == null) { return(false); } else { Stream resStream = new BufferedStream(res.GetResponseStream()); TimeStampResponse tsRes = new TimeStampResponse(resStream); resStream.Close(); try { tsRes.Validate(tsReq); resStream.Close(); return(true); } catch (TspException e) { resStream.Close(); return(false); } //saveresponse } }
private byte[] GetTimestampToken(byte[] imprint) { byte[] numArray; try { Licensing.ShowDemoMessage(); string value = (new Oid(this.TimeStamping.HashAlgorithm.ToString())).Value; TimeStampRequestGenerator timeStampRequestGenerator = new TimeStampRequestGenerator(); timeStampRequestGenerator.SetCertReq(true); if (this.TimeStamping.PolicyOid != null) { timeStampRequestGenerator.SetReqPolicy(this.TimeStamping.PolicyOid.Value.ToString()); } TimeStampRequest timeStampRequest = null; if (!this.TimeStamping.UseNonce) { timeStampRequest = timeStampRequestGenerator.Generate(value, imprint); } else { long tickCount = (long)Environment.TickCount; DateTime now = DateTime.Now; BigInteger bigInteger = BigInteger.ValueOf(tickCount + now.Ticks); timeStampRequest = timeStampRequestGenerator.Generate(value, imprint, bigInteger); } byte[] tSAResponse = this.GetTSAResponse(timeStampRequest.GetEncoded()); TimeStampResponse timeStampResponse = new TimeStampResponse(tSAResponse); timeStampResponse.Validate(timeStampRequest); if ((timeStampResponse.GetFailInfo() == null ? 0 : 1) != 0) { string[] invalidTimeStampingResponse = new string[] { CustomExceptions.InvalidTimeStampingResponse, "Status: ", null, null, null }; invalidTimeStampingResponse[2] = timeStampResponse.Status.ToString(); invalidTimeStampingResponse[3] = "; Status information : "; invalidTimeStampingResponse[4] = timeStampResponse.GetStatusString(); throw new WebException(string.Concat(invalidTimeStampingResponse)); } if (timeStampResponse.TimeStampToken == null) { throw new WebException(CustomExceptions.InvalidTimeStampingResponse); } numArray = tSAResponse; } catch { throw; } return(numArray); }
/** * Get timestamp token - Bouncy Castle request encoding / decoding layer */ protected internal byte[] GetTimeStampToken(byte[] imprint) { byte[] respBytes = null; // Setup the time stamp request TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator(); tsqGenerator.SetCertReq(true); // tsqGenerator.setReqPolicy("1.3.6.1.4.1.601.10.3.1"); BigInteger nonce = BigInteger.ValueOf(DateTime.Now.Ticks + Environment.TickCount); TimeStampRequest request = tsqGenerator.Generate(X509ObjectIdentifiers.IdSha1.Id, imprint, nonce); byte[] requestBytes = request.GetEncoded(); // Call the communications layer respBytes = GetTSAResponse(requestBytes); // Handle the TSA response TimeStampResponse response = new TimeStampResponse(respBytes); // validate communication level attributes (RFC 3161 PKIStatus) response.Validate(request); PkiFailureInfo failure = response.GetFailInfo(); int value = (failure == null) ? 0 : failure.IntValue; if (value != 0) { // @todo: Translate value of 15 error codes defined by PKIFailureInfo to string throw new Exception("Invalid TSA '" + tsaURL + "' response, code " + value); } // @todo: validate the time stap certificate chain (if we want // assure we do not sign using an invalid timestamp). // extract just the time stamp token (removes communication status info) TimeStampToken tsToken = response.TimeStampToken; if (tsToken == null) { throw new Exception("TSA '" + tsaURL + "' failed to return time stamp token: " + response.GetStatusString()); } TimeStampTokenInfo info = tsToken.TimeStampInfo; // to view details byte[] encoded = tsToken.GetEncoded(); // Update our token size estimate for the next call (padded to be safe) this.tokSzEstimate = encoded.Length + 32; return(encoded); }
public void TestCertReq() { TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( privateKey, cert, TspAlgorithms.MD5, "1.2"); tsTokenGen.SetCertificates(certs); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); // // request with certReq false // reqGen.SetCertReq(false); TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20], BigInteger.ValueOf(100)); TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed); TimeStampResponse tsResp = tsRespGen.Generate(request, BigInteger.ValueOf(23), DateTime.UtcNow); tsResp = new TimeStampResponse(tsResp.GetEncoded()); TimeStampToken tsToken = tsResp.TimeStampToken; Assert.IsNull(tsToken.TimeStampInfo.GenTimeAccuracy); // check for abscence of accuracy Assert.AreEqual("1.2", tsToken.TimeStampInfo.Policy); try { tsToken.Validate(cert); } catch (TspValidationException) { Assert.Fail("certReq(false) verification of token failed."); } IX509Store respCerts = tsToken.GetCertificates("Collection"); ICollection certsColl = respCerts.GetMatches(null); if (certsColl.Count != 0) { Assert.Fail("certReq(false) found certificates in response."); } }
private static void requestParse( byte[] request, string algorithm) { TimeStampRequest req = new TimeStampRequest(request); if (!req.MessageImprintAlgOid.Equals(algorithm)) { Assert.Fail("failed to get expected algorithm - got " + req.MessageImprintAlgOid + " not " + algorithm); } if (request != sha1Request && request != sha1noNonse) { if (!req.ReqPolicy.Equals(TspTestUtil.EuroPkiTsaTestPolicy.Id)) { Assert.Fail("" + algorithm + " failed policy check."); } if (request == ripemd160Request) { if (!req.CertReq) { Assert.Fail("" + algorithm + " failed certReq check."); } } } Assert.AreEqual(1, req.Version, "version not 1"); Assert.IsNull(req.GetCriticalExtensionOids(), "critical extensions found when none expected"); Assert.IsNull(req.GetNonCriticalExtensionOids(), "non-critical extensions found when none expected"); if (request != sha1noNonse) { if (req.Nonce == null) { Assert.Fail("" + algorithm + " nonse not found when one expected."); } } else { if (req.Nonce != null) { Assert.Fail("" + algorithm + " nonse not found when one not expected."); } } try { req.Validate(TspAlgorithms.Allowed, null, null); } catch (Exception) { Assert.Fail("validation exception."); } if (!Arrays.AreEqual(req.GetEncoded(), request)) { Assert.Fail("" + algorithm + " failed encode check."); } }