Esempio n. 1
0
        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);
        }
Esempio n. 2
0
        /// <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));
        }
Esempio n. 3
0
        private TimeStampRequest CreateRfc3161RequestBody(byte[] hash, string digestMethod)
        {
            String digestOid = CryptoConfig.MapNameToOID(CryptoConfig.CreateFromName(digestMethod).GetType().ToString());

            TimeStampRequestGenerator tsprg = new TimeStampRequestGenerator();

            tsprg.SetCertReq(true);
            return(tsprg.Generate(digestOid, hash));
        }
        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);
        }
Esempio n. 5
0
        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);
        }
Esempio n. 6
0
        /// <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);
        }
Esempio n. 7
0
        /// <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);
        }
Esempio n. 9
0
        /**
         * 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);
        }
Esempio n. 10
0
        /// <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>
        /// 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());
            }
        }
Esempio n. 12
0
        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
            }
        }
Esempio n. 13
0
 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);
 }
Esempio n. 14
0
        /**
         * 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);
        }
Esempio n. 15
0
        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.");
            }
        }
Esempio n. 16
0
        public virtual 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);

            byte[] requestBytes = request.GetEncoded();

            // Call the communications layer
            var respBytes = GetTSAResponse(requestBytes);

            // Handle the TSA response
            return(new TimeStampResponse(respBytes));
        }
        private void certReqTest(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs)
        {
            TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator(
                privateKey, cert, TspAlgorithms.MD5, "1.2");

            tsTokenGen.SetCertificates(certs);


            TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator();

            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.True("1.2".Equals(tsToken.TimeStampInfo.Policy));

            try
            {
                tsToken.Validate(cert);
            }
            catch (TspValidationException)
            {
                Assert.Fail("certReq(false) verification of token failed.");
            }

            IX509Store  store     = tsToken.GetCertificates();
            ICollection certsColl = store.GetMatches(null);

            if (certsColl.Count > 0)
            {
                Assert.Fail("certReq(false) found certificates in response.");
            }
        }
Esempio n. 18
0
        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());
                }
            }
        }
Esempio n. 19
0
        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());
        }
Esempio n. 20
0
        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());
        }
Esempio n. 21
0
        /// <summary>
        /// Returns DER encoded time-stamp request.
        /// </summary>
        /// <returns>Byte array containing DER encoded request.</returns>
        public byte[] ToByteArray()
        {
            TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator();
            TimeStampRequest          tsreq;

            tsqGenerator.SetCertReq(this.CertReq);
            if (!string.IsNullOrEmpty(this.ReqPolicy))
            {
                tsqGenerator.SetReqPolicy(this.ReqPolicy);
            }

            if (null == this.Nonce)
            {
                tsreq = tsqGenerator.Generate(this.MessageImprint.HashAlgorithm, this.MessageImprint.HashedMessage);
            }
            else
            {
                tsreq = tsqGenerator.Generate(this.MessageImprint.HashAlgorithm, this.MessageImprint.HashedMessage, new Org.BouncyCastle.Math.BigInteger(this.Nonce));
            }

            return(tsreq.GetEncoded());
        }
Esempio n. 22
0
        /// <summary>
        /// Ottiene un oggetto TimeStampRequest a partire dall'array di byte del documento da marcare
        /// </summary>
        /// <param name="filep7m"></param>
        /// <returns></returns>
        protected TimeStampRequest getTsReq(byte[] filep7m, DerObjectIdentifier oid)
        {
            TimeStampRequestGenerator tsqGen = new TimeStampRequestGenerator();

            //quando impostato a true significa che nella risposta della TSA deve essere incluso il certificato della firma
            tsqGen.SetCertReq(true);
            byte[] contentHash = null;

            //string algorithm = Org.BouncyCastle.Security.DigestUtilities.GetAlgorithmName(oid);
            string algorithm = oid.Id.ToString();

            contentHash = Org.BouncyCastle.Security.DigestUtilities.CalculateDigest(algorithm, filep7m);
            return(tsqGen.Generate(algorithm, contentHash));


            /*
             *
             * TimeStampRequest tsq = null;
             *
             * if (hashOid.Equals("1.3.14.3.2.26"))
             * {
             *  System.Security.Cryptography.SHA1 sh1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
             *  contentHash = sh1.ComputeHash(filep7m);
             *  tsq = tsqGen.Generate(TspAlgorithms.Sha1 , contentHash);
             * }
             * if (hashOid.Equals("2.16.840.1.101.3.4.2.1"))
             * {
             *  SHA256Managed sh256 = new SHA256Managed();
             *  contentHash = sh256.ComputeHash(filep7m);
             *  tsq = tsqGen.Generate(TspAlgorithms.Sha256, contentHash);
             * }
             *
             * //fra i parametri non metto il Nonce perchè questa è una verifica off-line!!!
             * //TimeStampRequest tsq = tsqGen.Generate(TspAlgorithms.Sha1, contentHash);
             *
             * return tsq;
             */
        }
            public byte[] GetTimeStampToken(byte[] imprint)
            {
                TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator();

                tsqGenerator.SetCertReq(true);

                BigInteger nonce = BigInteger.ValueOf((long)(new TimeSpan(DateTime.Now.Ticks)).TotalMilliseconds);

                TimeStampRequest request = tsqGenerator.Generate(new DerObjectIdentifier(
                                                                     DigestAlgorithms.GetAllowedDigest(DEFAULTHASHALGORITHM)),
                                                                 imprint, nonce);

                JObject time = Timestamp(baseURL, Hex.ToHexString(request.GetMessageImprintDigest()),
                                         accessToken);
                String tst = (String)time.GetValue("token");

                byte[] token = Base64.Decode(tst);

                CmsSignedData cms = new CmsSignedData(token);

                TimeStampToken tstToken = new TimeStampToken(cms);

                return(tstToken.GetEncoded());
            }
Esempio n. 24
0
		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.");
			}
		}
Esempio n. 25
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="TimeStampQuery"></param>
        /// <returns></returns>
        public OutputResponseMarca getTimeStamp(InputMarca TimeStampQuery)
        {
            OutputResponseMarca outputMarca = new OutputResponseMarca();


            byte[] dati = String_To_Bytes(TimeStampQuery.file_p7m);
            //SHA1 sha1 = SHA1CryptoServiceProvider.Create();
            //byte[] hash = sha1.ComputeHash(dati);

            SHA256Managed sha256 = new SHA256Managed();

            byte[] hash = sha256.ComputeHash(dati);

            TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator();

            reqGen.SetCertReq(true);


            //Funzione randomica per il Nonce.
            //RandomNumberGenerator nRand = new RNGCryptoServiceProvider();
            long casuale = (long)nRandom.Next();
            //TimeStampRequest tsReq = reqGen.Generate(TspAlgorithms.Sha1, hash, BigInteger.ValueOf(casuale));
            TimeStampRequest tsReq = reqGen.Generate(TspAlgorithms.Sha256, hash, BigInteger.ValueOf(casuale));

            byte[] tsData = tsReq.GetEncoded();

            string urlTSA = string.Empty;

            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["URL_TSA"]))
            {
                urlTSA = ConfigurationManager.AppSettings["URL_TSA"].ToString();
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(urlTSA);
                req.Method      = "POST";
                req.ContentType = "application/timestamp-query";

                //Username e password per accedere alla Time Stamping Authority
                string pwd = string.Empty;
                if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["PASSWORD_UTENTE_TSA"]))
                {
                    pwd = ConfigurationManager.AppSettings["PASSWORD_UTENTE_TSA"].ToString();
                    req.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(pwd)));
                }

                req.ContentLength = tsData.Length;

                Stream reqStream = req.GetRequestStream();
                reqStream.Write(tsData, 0, tsData.Length);
                reqStream.Close();

                HttpWebResponse res = (HttpWebResponse)req.GetResponse();
                if (res == null)
                {
                    outputMarca.esito             = "KO";
                    outputMarca.descrizioneErrore = "Impossibile contattare la TSA o autorizzazione negata";
                    return(outputMarca);
                }
                else
                {
                    Stream            resStream = new BufferedStream(res.GetResponseStream());
                    TimeStampResponse tsRes     = new TimeStampResponse(resStream);
                    resStream.Close();
                    BusinessLogic.Documenti.DigitalSignature.VerifyTimeStamp checkMarca = new BusinessLogic.Documenti.DigitalSignature.VerifyTimeStamp();
                    outputMarca = checkMarca.Verify(tsReq, tsRes);
                }
            }
            else
            {
                outputMarca.esito             = "KO";
                outputMarca.descrizioneErrore = "Impossibile contattare la TSA o url configurata errata!";
                return(outputMarca);
            }

            return(outputMarca);
        }
Esempio n. 26
0
        /// <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);
        }
Esempio n. 27
0
        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);
        }
Esempio n. 28
0
		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);
		}