コード例 #1
0
ファイル: CarimboBry.cs プロジェクト: radtek/digitalsign
        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);
        }
コード例 #2
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)
        {
            byte[] respBytes = null;
            // Setup the time stamp request
            TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator();

            tsqGenerator.SetCertReq(true);
            if (!string.IsNullOrEmpty(tsaReqPolicy))
            {
                tsqGenerator.SetReqPolicy(tsaReqPolicy);
            }
            // tsqGenerator.setReqPolicy("1.3.6.1.4.1.601.10.3.1");
            BigInteger       nonce   = BigInteger.ValueOf(DateTime.Now.Ticks + Environment.TickCount);
            TimeStampRequest request = tsqGenerator.Generate(DigestAlgorithms.GetAllowedDigests(digestAlgorithm), imprint, nonce);

            byte[] requestBytes = request.GetEncoded();

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

            // Handle the TSA response
            TimeStampResponse response = new TimeStampResponse(respBytes);

            // validate communication level attributes (RFC 3161 PKIStatus)
            response.Validate(request);
            PkiFailureInfo failure = response.GetFailInfo();
            int            value   = (failure == null) ? 0 : failure.IntValue;

            if (value != 0)
            {
                // @todo: Translate value of 15 error codes defined by PKIFailureInfo to string
                throw new IOException(MessageLocalization.GetComposedMessage("invalid.tsa.1.response.code.2", tsaURL, value));
            }
            // @todo: validate the time stap certificate chain (if we want
            //        assure we do not sign using an invalid timestamp).

            // extract just the time stamp token (removes communication status info)
            TimeStampToken tsToken = response.TimeStampToken;

            if (tsToken == null)
            {
                throw new IOException(MessageLocalization.GetComposedMessage("tsa.1.failed.to.return.time.stamp.token.2", tsaURL, response.GetStatusString()));
            }
            TimeStampTokenInfo tsTokenInfo = tsToken.TimeStampInfo; // to view details

            byte[] encoded = tsToken.GetEncoded();

            LOGGER.Info("Timestamp generated: " + tsTokenInfo.GenTime);
            if (tsaInfo != null)
            {
                tsaInfo.InspectTimeStampTokenInfo(tsTokenInfo);
            }
            // Update our token size estimate for the next call (padded to be safe)
            this.tokenSizeEstimate = encoded.Length + 32;
            return(encoded);
        }
コード例 #3
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);
        }
コード例 #4
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
        }
コード例 #5
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);
 }
コード例 #6
0
ファイル: X509Utils.cs プロジェクト: tixsys/esteid
        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());
        }
コード例 #7
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());
        }
コード例 #8
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.");
            }
        }
コード例 #9
0
ファイル: TSPTest.cs プロジェクト: KimikoMuffin/bc-csharp
		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.");
			}
		}
コード例 #10
0
        private void extensionTest(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs)
        {
            TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator(
                privateKey, cert, TspAlgorithms.Sha1, "1.2");

            tsTokenGen.SetCertificates(certs);

            TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator();

            // --- These are test case only values
            reqGen.SetReqPolicy("2.5.29.56");
            reqGen.AddExtension(new DerObjectIdentifier("1.3.6.1.5.5.7.1.2"), true, new DerOctetString(new byte[20]));
            // --- not for any real world purpose.

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

            try
            {
                request.Validate(new ArrayList(), new ArrayList(), new ArrayList());
                Assert.Fail("expected exception");
            } catch (Exception ex)
            {
                Assert.True("request contains unknown algorithm" == ex.Message);
            }

            ArrayList algorithms = new ArrayList();

            algorithms.Add(TspAlgorithms.Sha1);

            try
            {
                request.Validate(algorithms, new ArrayList(), new ArrayList());
                Assert.Fail("no exception");
            }
            catch (Exception e)
            {
                Assert.IsTrue(e.Message == "request contains unknown policy");
            }

            ArrayList policies = new ArrayList();

            // Testing only do not use in real world.
            policies.Add("2.5.29.56");

            try
            {
                request.Validate(algorithms, policies, new ArrayList());
                Assert.Fail("no exception");
            }
            catch (Exception e)
            {
                Assert.IsTrue(e.Message == "request contains unknown extension");
            }

            ArrayList extensions = new ArrayList();

            // Testing only do not use in real world/
            extensions.Add("1.3.6.1.5.5.7.1.2");


            // should validate with full set
            request.Validate(algorithms, policies, extensions);

            // should validate with null policy
            request.Validate(algorithms, null, extensions);

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

            TimeStampResponse tsResp = tsRespGen.Generate(request, new BigInteger("23"), DateTime.UtcNow);

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

            TimeStampToken tsToken = tsResp.TimeStampToken;

            tsToken.Validate(cert);

            Asn1.Cms.AttributeTable table = tsToken.SignedAttributes;

            Assert.NotNull(table[PkcsObjectIdentifiers.IdAASigningCertificate], "no signingCertificate attribute found");
        }