public byte[] GetTimeStampToken(byte[] imprint) { byte[] respBytes = null; var tsqGenerator = new TimeStampRequestGenerator(); tsqGenerator.SetCertReq(true); tsqGenerator.SetReqPolicy("2.16.76.1.6.6"); var nonce = BigInteger.ValueOf(DateTime.Now.Ticks + Environment.TickCount); var request = tsqGenerator.Generate(DigestAlgorithms.GetAllowedDigest(this.digestAlgorithm), imprint, nonce); var requestBytes = request.GetEncoded(); respBytes = this.GetTsaResponse(requestBytes); var response = new TimeStampResponse(respBytes); response.Validate(request); var failure = response.GetFailInfo(); var value = (failure == null) ? 0 : failure.IntValue; if (value != 0) { //// @todo: Translate value of 15 error codes defined by PKIFailureInfo to string var mensagem = string.Format( "invalid.tsa.1.response.code.2 {0} {1}", this.url, response.GetStatusString()); throw new IOException(mensagem); } //// @todo: validate the time stap certificate chain (if we want assure we do not sign using an invalid timestamp). var timeStampToken = response.TimeStampToken; if (timeStampToken == null) { var mensagem = string.Format("tsa.1.failed.to.return.time.stamp.token.2 {0} {1}", this.url, response.GetStatusString()); throw new IOException(mensagem); } var timeStampInfo = timeStampToken.TimeStampInfo; var encoded = timeStampToken.GetEncoded(); Console.WriteLine("Timestamp generated: " + timeStampInfo.GenTime); if (this.tsaInfo != null) { this.tsaInfo.InspectTimeStampTokenInfo(timeStampInfo); } this.tokenSizeEstimate = encoded.Length + 32; return(encoded); }
public byte[] GetTimeStampToken(byte[] imprint) { byte[] respBytes = null; //// Setup the time stamp request var tsqGenerator = new TimeStampRequestGenerator(); tsqGenerator.SetCertReq(true); //// tsqGenerator.setReqPolicy("1.3.6.1.4.1.601.10.3.1"); var nonce = BigInteger.ValueOf(DateTime.Now.Ticks + Environment.TickCount); var request = tsqGenerator.Generate(DigestAlgorithms.GetAllowedDigests(this.digestAlgorithm), imprint, nonce); var requestBytes = request.GetEncoded(); //// Call the communications layer respBytes = this.GetTsaResponse(requestBytes); //// Handle the TSA response var response = new TimeStampResponse(respBytes); //// validate communication level attributes (RFC 3161 PKIStatus) response.Validate(request); var failure = response.GetFailInfo(); var 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", this.url, 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) var timeStampToken = response.TimeStampToken; if (timeStampToken == null) { throw new IOException(MessageLocalization.GetComposedMessage("tsa.1.failed.to.return.time.stamp.token.2", this.url, response.GetStatusString())); } var timeStampInfo = timeStampToken.TimeStampInfo; // to view details var encoded = timeStampToken.GetEncoded(); Log.Application.Info("Timestamp generated: " + timeStampInfo.GenTime); if (this.tsaInfo != null) { this.tsaInfo.InspectTimeStampTokenInfo(timeStampInfo); } //// Update our token size estimate for the next call (padded to be safe) this.tokenSizeEstimate = encoded.Length + 32; return(encoded); }
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); }
/// <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); }
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); }
/** * 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) { // 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(TsaDigestAlgorithmOID, imprint, nonce); byte[] requestBytes = request.GetEncoded(); // Call the communications layer var respBytes = GetTSAResponse(requestBytes); // Handle the TSA response TimeStampResponse response = new TimeStampResponse(respBytes); // validate communication level attributes (RFC 3161 PKIStatus) response.Validate(request); var 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($"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($"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) tokenSizeEstimate = encoded.Length + 32; return(encoded); }
/// <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()); } }
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 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 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); }
private byte[] ParseRfc3161ResponseBody(byte[] rspBody, TimeStampRequest tspr) { TimeStampResponse tsResponse = new TimeStampResponse(rspBody); trace.TraceData(TraceEventType.Verbose, 0, "retrieved time-stamp response", address.ToString(), Convert.ToBase64String(tsResponse.GetEncoded())); try { tsResponse.Validate(tspr); } catch (Exception e) { trace.TraceEvent(TraceEventType.Error, 0, "The time-stamp response does not correspond with the request: {0}", e.Message); throw e; } return(tsResponse.TimeStampToken.GetEncoded()); }
private byte[] GenerateTimestampToken(byte[] signature, Uri timestampUri) { Log.Trace($"Timestamping with server: ${timestampUri}"); var request = WebRequest.CreateHttp(timestampUri); request.ContentType = "application/timestamp-query"; request.Method = "POST"; request.Timeout = 15000; var timeStampRequestGenerator = new TimeStampRequestGenerator(); timeStampRequestGenerator.SetCertReq(true); using (var hasher = new SHA1Managed()) { signature = hasher.ComputeHash(signature); } var timestampRequest = timeStampRequestGenerator.Generate(TspAlgorithms.Sha1, signature, new BigInteger(64, Random)); var timestampRequestRaw = timestampRequest.GetEncoded(); request.ContentLength = timestampRequestRaw.Length; using (var requestStream = request.GetRequestStream()) { requestStream.Write(timestampRequestRaw, 0, timestampRequestRaw.Length); } using (var response = request.GetResponse()) { var responseStream = response.GetResponseStream(); if (responseStream == null) { throw new IOException("Timestmap server did not contain any response data"); } using (var bufferedResponseStream = new BufferedStream(responseStream)) { var timestampResponse = new TimeStampResponse(bufferedResponseStream); timestampResponse.Validate(timestampRequest); Log.Trace("Timestamping done"); return(timestampResponse.TimeStampToken.GetEncoded()); } } }
private static bool ValidateTimestamp(TimeStampResponse tr, byte[] hash) { try { TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); TimeStampRequest request = reqGen.Generate( TspAlgorithms.Sha1, hash, BigInteger.ValueOf(100) ); tr.Validate(request); } catch (Exception ex) { Console.WriteLine(ex.Message); return(false); } return(tr.GetFailInfo() == null); }
public const String ID_TIME_STAMP_TOKEN = "1.2.840.113549.1.9.16.2.14"; // RFC 3161 id-aa-timeStampToken static public byte[] GetTimestampToken(String tsaURL, string tsaUserName, string tsaPassword, byte[] imprint, ref string error) { 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); TimeStampRequest request = tsqGenerator.Generate(X509ObjectIdentifiers.IdSha1.Id, imprint, nonce); byte[] requestBytes = request.GetEncoded(); byte[] responseBytes = GetTSAResponse(tsaURL, tsaUserName, tsaPassword, requestBytes); TimeStampResponse response = new TimeStampResponse(responseBytes); response.Validate(request); PkiFailureInfo failure = response.GetFailInfo(); int value = (failure == null) ? 0 : failure.IntValue; if (value != 0) { error = string.Format(Resources.TSA_URL_ERROR, tsaURL, value); return(null); } TimeStampToken tsToken = response.TimeStampToken; if (tsToken == null) { error = string.Format(Resources.TSA_READ_ERROR, tsaURL); return(null); } return(tsToken.GetEncoded()); }
public byte[] GetTimeStamp(byte[] hash, DigestMethod digestMethod, bool certReq) { TimeStampRequestGenerator timeStampRequestGenerator = new TimeStampRequestGenerator(); timeStampRequestGenerator.SetCertReq(certReq); BigInteger nonce = BigInteger.ValueOf(DateTime.Now.Ticks); TimeStampRequest timeStampRequest = timeStampRequestGenerator.Generate(digestMethod.Oid, hash, nonce); byte[] encoded = timeStampRequest.GetEncoded(); HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(_url); httpWebRequest.Method = "POST"; httpWebRequest.ContentType = "application/timestamp-query"; httpWebRequest.ContentLength = encoded.Length; if (!string.IsNullOrEmpty(_user) && !string.IsNullOrEmpty(_password)) { string s = $"{_user}:{_password}"; httpWebRequest.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(s), Base64FormattingOptions.None); } Stream requestStream = httpWebRequest.GetRequestStream(); requestStream.Write(encoded, 0, encoded.Length); requestStream.Close(); HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); if (httpWebResponse.StatusCode != HttpStatusCode.OK) { throw new Exception("El servidor ha devuelto una respuesta no válida"); } Stream stream = new BufferedStream(httpWebResponse.GetResponseStream()); TimeStampResponse timeStampResponse = new TimeStampResponse(stream); stream.Close(); timeStampResponse.Validate(timeStampRequest); if (timeStampResponse.TimeStampToken == null) { throw new Exception("El servidor no ha devuelto ningún sello de tiempo"); } return(timeStampResponse.TimeStampToken.GetEncoded()); }
/// <summary> /// Questo metodo verifica se l'associazione fra marca e file è valida, verifica inoltre la /// validità del certificato firmatario della marca e la data di scadenza della marca; infine /// restituisce (se le verifiche vanno a buon fine) tutti i dati contenuti nella marca. /// </summary> /// <param name="tsRes"></param> /// <param name="tsReq"></param> /// <returns></returns> protected OutputResponseMarca checkMarca(TimeStampResponse tsRes, TimeStampRequest tsReq) { OutputResponseMarca outTSR = new OutputResponseMarca(); try { tsRes.Validate(tsReq); outTSR.esito = "OK"; outTSR.descrizioneErrore = string.Empty; } catch (TspException e) { outTSR.esito = "KO"; outTSR.descrizioneErrore = "verifica della marca fallita: " + e.Message; logger.Debug("verifica della marca fallita: " + e.Message); //return outTSR; } TimeStampToken tsToken = tsRes.TimeStampToken; //Verifica data scadenza marca secondo l'ora locale Org.BouncyCastle.X509.Store.IX509Store store = tsToken.GetCertificates("Collection"); Org.BouncyCastle.X509.X509Certificate cert = (Org.BouncyCastle.X509.X509Certificate) new ArrayList(store.GetMatches(tsToken.SignerID))[0]; //se la data attuale è maggiore di quella di scadenza del certificato che ha firmato la marca //allora la marca è scaduta!!! if (DateTime.Now.CompareTo(cert.NotAfter.ToLocalTime()) > 0) { //outTSR.esito = "KO"; outTSR.descrizioneErrore = "marca temporale scaduta"; logger.Debug("marca temporale scaduta"); //return outTSR; } try { //estrazione delle informazioni dalla marca outTSR.dsm = cert.NotAfter.ToLocalTime().ToString(); outTSR.sernum = tsToken.TimeStampInfo.SerialNumber.ToString(); outTSR.fhash = byteArrayToHexa(tsToken.TimeStampInfo.TstInfo.MessageImprint.GetHashedMessage()); outTSR.docm = tsToken.TimeStampInfo.TstInfo.GenTime.TimeString; outTSR.docm_date = tsToken.TimeStampInfo.GenTime.ToLocalTime().ToString(); outTSR.marca = Convert.ToBase64String(tsRes.GetEncoded()); outTSR.algCertificato = cert.SigAlgName; outTSR.fromDate = cert.NotBefore.ToLocalTime().ToString(); outTSR.snCertificato = cert.SerialNumber.ToString(); //Algoritmo hash utilizzato per l'impronta string algHashOid = tsToken.TimeStampInfo.MessageImprintAlgOid; if (!string.IsNullOrEmpty(algHashOid)) { System.Security.Cryptography.Oid oidHash = new System.Security.Cryptography.Oid(algHashOid); outTSR.algHash = oidHash.FriendlyName; } outTSR.TSA = new TSARFC2253(); //Con le TSA di test potrebbe non essere valorizzato l'oggetto TSA logger.Debug("Controllo TSA : " + tsToken.TimeStampInfo.Tsa); try { if (tsToken.TimeStampInfo.Tsa != null) { string oid = string.Empty; string oidValue = string.Empty; logger.Debug("TagNo: " + tsToken.TimeStampInfo.Tsa.TagNo); for (int n = 0; n < tsToken.TimeStampInfo.Tsa.TagNo; n++) { logger.Debug("Tag: " + n); Org.BouncyCastle.Asn1.Asn1Sequence seq = (Org.BouncyCastle.Asn1.Asn1Sequence)tsToken.TimeStampInfo.Tsa.Name.ToAsn1Object(); //Obsoleto //Org.BouncyCastle.Asn1.Asn1Object obj = (Org.BouncyCastle.Asn1.Asn1Object)seq.GetObjectAt(n); Org.BouncyCastle.Asn1.Asn1Object obj = (Org.BouncyCastle.Asn1.Asn1Object)seq[n]; Org.BouncyCastle.Asn1.Asn1Set set1 = (Org.BouncyCastle.Asn1.Asn1Set)obj.ToAsn1Object(); //Obsoleto //seq = (Org.BouncyCastle.Asn1.Asn1Sequence)set1.GetObjectAt(0); //obj = (Org.BouncyCastle.Asn1.Asn1Object)seq.GetObjectAt(0); seq = (Org.BouncyCastle.Asn1.Asn1Sequence)set1[0]; obj = (Org.BouncyCastle.Asn1.Asn1Object)seq[0]; oid = obj.ToString(); //Obsoleto //obj = (Org.BouncyCastle.Asn1.Asn1Object)seq.GetObjectAt(1); obj = (Org.BouncyCastle.Asn1.Asn1Object)seq[1]; oidValue = obj.ToString(); System.Security.Cryptography.Oid oid_obj = new System.Security.Cryptography.Oid(oid); string friendly = oid_obj.FriendlyName; logger.Debug("oid: " + oid + " friendly: " + friendly); switch (friendly) { case "CN": outTSR.TSA.CN = oidValue; break; case "OU": outTSR.TSA.OU = oidValue; break; case "O": outTSR.TSA.O = oidValue; break; case "C": outTSR.TSA.C = oidValue; break; } } outTSR.TSA.TSARFC2253Name = "CN=" + outTSR.TSA.CN + ",OU=" + outTSR.TSA.OU + ",O=" + outTSR.TSA.O + ",C=" + outTSR.TSA.C; } } catch (Exception e) { logger.Debug("Eccezione controllo TSA : " + e.Message); } logger.Debug("Fine Controllo TSA"); } catch (Exception eTsp) { outTSR.esito = "KO"; outTSR.descrizioneErrore = "estrazione delle informazioni dalla marca fallita: " + eTsp.Message; logger.Debug("estrazione delle informazioni dalla marca fallita: " + eTsp.Message); //return outTSR; } //verifico l'esistenza del documento al quale è associata la marca temporale //Commentata perchè l'impronta del documento è ancora calcolata con SHA1 invece che SHA256 //DocsPaDB.Query_DocsPAWS.Documenti documento = new DocsPaDB.Query_DocsPAWS.Documenti(); //outTSR.timestampedDoc = documento.GetDocNumberByImpronta(outTSR.fhash); //if (string.IsNullOrEmpty(outTSR.timestampedDoc)) //{ // outTSR.timestampedDoc = "Non esiste alcun documento associato alla marca temporale."; //} //costruisco l'oggetto rappresentante il contenuto in chiaro della marca outTSR.DecryptedTSR = new Marca(); outTSR.DecryptedTSR.content = contentMarca(outTSR); outTSR.DecryptedTSR.contentType = "text/html"; //"application/x-html"; outTSR.DecryptedTSR.length = outTSR.DecryptedTSR.content.Length; return(outTSR); }
/// <summary> /// Creates timestamp from provided data. /// </summary> /// <returns> /// <see cref="TimestampObject" /> /// </returns> /// <exception cref="System.ArgumentNullException"> /// Hash algorithm not provided. /// or /// TSA URL not provided. /// or /// Timestamp output format not provided. /// or /// Data for timestamping not provided.</exception> /// <exception cref="AbsoluteTimestamp.TimestampException">Cannot connect to TSA server.</exception> /// <exception cref="TspValidationException"></exception> public TimestampObject CreateTimestamp() { /* Check that everything has been provided */ if (0 == this.hashAlgorithm) { throw new ArgumentNullException("Hash algorithm not provided."); } if (String.IsNullOrWhiteSpace(this.tsaPrimaryUrl) && String.IsNullOrWhiteSpace(this.tsaSecondaryUrl)) { throw new ArgumentNullException("TSA URL not provided."); } if (0 == this.outputFormat) { throw new ArgumentNullException("Timestamp output format not provided."); } if (null == this.timestampData) { throw new ArgumentNullException("Data for timestamping not provided."); } /* Get hashed data */ byte[] hashedData = this.timestampData.GetHashedData(this.hashAlgorithm); /* Generate request */ TimeStampRequestGenerator requestGenerator = new TimeStampRequestGenerator(); requestGenerator.SetCertReq(true); TimeStampRequest request = requestGenerator.Generate(new Oid(this.hashAlgorithm.ToString()).Value, hashedData); /* Get response */ TimeStampResponse response = GetTimeStampResponse(request); /* Validate response */ if (!(response.Status == 0 || response.Status == 1)) { throw new TspValidationException( string.Format("Invalid response, response status={0}, response status string={1}, response failure info={2}", response.Status, response.GetStatusString(), response.GetFailInfo().IntValue)); } /* * Check this response against to see if it a well formed response for * the passed in request. It validates message imprint digests and message imprint algorithms. * * @param request the request to be checked against * @throws TspException if the request can not match this response. */ response.Validate(request); TimeStampToken token = response.TimeStampToken; X509Certificate2 certificate = null; TimestampObject timestamp = new TimestampObject(); /* Validate certificate */ certificate = TimestampVerifier.ValidateCertificate(token, timestamp, minimumCertificateValidityPeriod); timestamp.HashAlgorithm = this.hashAlgorithm; timestamp.Timestamp = Utils.GetTimestampForOutput(response, this.outputFormat, this.timestampData); return(timestamp); }
public void TestResponseValidation() { TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( privateKey, cert, TspAlgorithms.MD5, "1.2"); 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()); TimeStampToken tsToken = tsResp.TimeStampToken; tsToken.Validate(cert); // // check validation // tsResp.Validate(request); try { request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20], BigInteger.ValueOf(101)); tsResp.Validate(request); Assert.Fail("response validation failed on invalid nonce."); } catch (TspValidationException) { // ignore } try { request = reqGen.Generate(TspAlgorithms.Sha1, new byte[22], BigInteger.ValueOf(100)); tsResp.Validate(request); Assert.Fail("response validation failed on wrong digest."); } catch (TspValidationException) { // ignore } try { request = reqGen.Generate(TspAlgorithms.MD5, new byte[20], BigInteger.ValueOf(100)); tsResp.Validate(request); Assert.Fail("response validation failed on wrong digest."); } catch (TspValidationException) { // ignore } }
public void TestAccuracyWithCertsAndOrdering() { TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( privateKey, cert, TspAlgorithms.MD5, "1.2.3"); tsTokenGen.SetCertificates(certs); tsTokenGen.SetAccuracySeconds(3); tsTokenGen.SetAccuracyMillis(1); tsTokenGen.SetAccuracyMicros(2); tsTokenGen.SetOrdering(true); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); reqGen.SetCertReq(true); TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20], BigInteger.ValueOf(100)); Assert.IsTrue(request.CertReq); 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(3, accuracy.Seconds); Assert.AreEqual(1, accuracy.Millis); Assert.AreEqual(2, accuracy.Micros); Assert.AreEqual(BigInteger.ValueOf(23), tstInfo.SerialNumber); Assert.AreEqual("1.2.3", tstInfo.Policy); Assert.AreEqual(true, tstInfo.IsOrdered); Assert.AreEqual(tstInfo.Nonce, BigInteger.ValueOf(100)); // // test certReq // IX509Store store = tsToken.GetCertificates("Collection"); ICollection certificates = store.GetMatches(null); Assert.AreEqual(2, certificates.Count); }