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.");
            }
        }
示例#2
0
        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 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.");
            }
        }
示例#4
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);
        }
        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);
        }
示例#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);
        }
示例#7
0
        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
        }
        /**
         * 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);
        }
示例#9
0
文件: ParseTest.cs 项目: ekr/hacrypto
        private static void unacceptableResponseParse(
            byte[] response)
        {
            TimeStampResponse resp = new TimeStampResponse(response);

            if (resp.Status != (int)PkiStatus.Rejection)
            {
                Assert.Fail("request not rejected.");
            }

            if (resp.GetFailInfo().IntValue != PkiFailureInfo.UnacceptedPolicy)
            {
                Assert.Fail("request not rejected.");
            }
        }
示例#10
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);
 }
示例#11
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);
        }
        private void timeNotAvailableTest(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[20]);

            TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed);

            TimeStampResponse tsResp = null;


            //
            // This is different to the java api.
            // the java version has two calls, generateGrantedResponse and generateRejectedResponse
            // See line 726 of NewTspTest
            //

            tsResp = tsRespGen.Generate(request, new BigInteger("23"), null);

            tsResp = new TimeStampResponse(tsResp.GetEncoded());

            TimeStampToken tsToken = tsResp.TimeStampToken;

            if (tsToken != null)
            {
                Assert.Fail("timeNotAvailable - token not null.");
            }

            PkiFailureInfo failInfo = tsResp.GetFailInfo();

            if (failInfo == null)
            {
                Assert.Fail("timeNotAvailable - failInfo set to null.");
            }

            if (failInfo.IntValue != PkiFailureInfo.TimeNotAvailable)
            {
                Assert.Fail("timeNotAvailable - wrong failure info returned.");
            }
        }
        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);
        }
示例#14
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());
        }
        private void badPolicyTest(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs)
        {
            TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator(
                privateKey, cert, TspAlgorithms.Sha1, "1.2");

            tsTokenGen.SetCertificates(certs);


            TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator();

            reqGen.SetReqPolicy("1.1");
            TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20]);

            TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed, new ArrayList());

            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.");
            }
        }
示例#16
0
        public void TestTimeNotAvailable()
        {
            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, new BigInteger("23"), null);

            tsResp = new TimeStampResponse(tsResp.GetEncoded());

            TimeStampToken tsToken = tsResp.TimeStampToken;

            if (tsToken != null)
            {
                Assert.Fail("timeNotAvailable - token not null.");
            }

            PkiFailureInfo failInfo = tsResp.GetFailInfo();

            if (failInfo == null)
            {
                Assert.Fail("timeNotAvailable - failInfo set to null.");
            }

            if (failInfo.IntValue != PkiFailureInfo.TimeNotAvailable)
            {
                Assert.Fail("timeNotAvailable - wrong failure info returned.");
            }
        }
示例#17
0
		private static void unacceptableResponseParse(
			byte[] response)
		{
			TimeStampResponse resp = new TimeStampResponse(response);

			if (resp.Status != (int) PkiStatus.Rejection)
			{
				Assert.Fail("request not rejected.");
			}

			if (resp.GetFailInfo().IntValue != PkiFailureInfo.UnacceptedPolicy)
			{
				Assert.Fail("request not rejected.");
			}
		}
示例#18
0
		public void TestBadPolicy()
		{
			TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator(
				privateKey, cert, TspAlgorithms.Sha1, "1.2");

			tsTokenGen.SetCertificates(certs);

			TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator();

			reqGen.SetReqPolicy("1.1");

			TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20]);

			TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed, new ArrayList());

			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.");
			}
		}
示例#19
0
		public void TestTimeNotAvailable()
		{
			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, new BigInteger("23"), null);

			tsResp = new TimeStampResponse(tsResp.GetEncoded());

			TimeStampToken tsToken = tsResp.TimeStampToken;

			if (tsToken != null)
			{
				Assert.Fail("timeNotAvailable - token not null.");
			}

			PkiFailureInfo failInfo = tsResp.GetFailInfo();

			if (failInfo == null)
			{
				Assert.Fail("timeNotAvailable - failInfo set to null.");
			}

			if (failInfo.IntValue != PkiFailureInfo.TimeNotAvailable)
			{
				Assert.Fail("timeNotAvailable - wrong failure info returned.");
			}
		}
示例#20
0
		public void TestIncorrectHash()
		{
			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;

			if (tsToken != null)
			{
				Assert.Fail("incorrectHash - 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.");
			}
		}
示例#21
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);
        }