Ejemplo n.º 1
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);
 }
        private void tokenEncodingTest(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs)
        {
            TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator(
                privateKey, cert, TspAlgorithms.Sha1, "1.2.3.4.5.6");

            tsTokenGen.SetCertificates(certs);


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

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

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

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

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

            if (!Arrays.AreEqual(tsResponse.GetEncoded(), tsResp.GetEncoded()) ||
                !Arrays.AreEqual(tsResponse.TimeStampToken.GetEncoded(),
                                 tsResp.TimeStampToken.GetEncoded()))
            {
                Assert.Fail();
            }
        }
Ejemplo n.º 3
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 basicTestWithTSA(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs)
        {
            TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator(
                privateKey, cert, TspAlgorithms.Sha1, "1.2");

            tsTokenGen.SetCertificates(certs);
            tsTokenGen.SetTsa(new Asn1.X509.GeneralName(new X509Name("CN=Test")));

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

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

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

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

            TimeStampToken tsToken = tsResp.TimeStampToken;

            tsToken.Validate(cert);

            Asn1.Cms.AttributeTable table = tsToken.SignedAttributes;

            Assert.IsNotNull(table[PkcsObjectIdentifiers.IdAASigningCertificate], "no signingCertificate attribute found");
        }
Ejemplo n.º 5
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));
        }
        private async Task <TimestampResult> BouncyCastleTimeStamp(Uri timestampServer, HashAlgorithmName timestampAlgorithm, TimestampNonceFactory nonce)
        {
            var oid = HashAlgorithmTranslator.TranslateFromNameToOid(timestampAlgorithm);
            var requestGenerator = new TimeStampRequestGenerator();

            var(signatureDocument, timestampSubject) = GetSignatureToTimestamp(_part);
            using (var hash = HashAlgorithmTranslator.TranslateFromNameToxmlDSigUri(timestampAlgorithm, out _))
            {
                var digest         = hash.ComputeHash(timestampSubject);
                var request        = requestGenerator.Generate(oid.Value, digest, new Org.BouncyCastle.Math.BigInteger(nonce.Nonce));
                var encodedRequest = request.GetEncoded();
                var client         = new HttpClient();
                var content        = new ByteArrayContent(encodedRequest);
                content.Headers.Add("Content-Type", "application/timestamp-query");
                var post = await client.PostAsync(timestampServer, content);

                if (post.StatusCode != HttpStatusCode.OK)
                {
                    return(TimestampResult.Failed);
                }
                var responseBytes = await post.Content.ReadAsByteArrayAsync();

                var responseParser    = new Asn1StreamParser(responseBytes);
                var timeStampResponse = new TimeStampResponse(responseBytes);
                var tokenResponse     = timeStampResponse.TimeStampToken.GetEncoded();
                ApplyTimestamp(signatureDocument, _part, tokenResponse);
                return(TimestampResult.Success);
            }
        }
Ejemplo n.º 7
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);
        }
Ejemplo n.º 8
0
        private TimeStampResponse getTimeStamp(string URL)
        {
            //RFC3161 compliant Time Stamp Authority (TSA) server
            TimeStampResponse response = null;

            byte[] sha1Digest = new byte [20];
            TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator();

            //SecureRandom randomGenerator = SecureRandom.GetInstance("SHA1PRNG");
            //long nonce = randomGenerator.NextLong();


            Org.BouncyCastle.Asn1.DerObjectIdentifier oDR = new Org.BouncyCastle.Asn1.DerObjectIdentifier("1.3.6.1.4.1.311.3.2.1");
            // request with digestAlgorithmOID, byte[] digest, java.math.BigInteger nonc
            //byte[] digest = TSToken.TimeStampInfo.GetMessageImprintDigest();

            TimeStampRequest request = reqGen.Generate(oDR, sha1Digest, Org.BouncyCastle.Math.BigInteger.ValueOf(100));

            byte[]     reqData = request.GetEncoded();
            WebRequest conn    = WebRequest.Create(URL);
            Stream     st      = conn.GetRequestStream();

            st.Write(reqData, 0, reqData.Length);
            st.Flush();
            st.Close();
            var    resposta  = conn.GetResponse();
            Stream stReponse = resposta.GetResponseStream();

            response = new TimeStampResponse(stReponse);
            stReponse.Close();
            return(response);
        }
        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.");
            }
        }
        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.");
            }
        }
Ejemplo n.º 11
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);
        }
Ejemplo n.º 12
0
        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);
        }
Ejemplo n.º 13
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));
        }
Ejemplo n.º 14
0
        public void TestAccuracyZeroCerts()
        {
            TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator(
                privateKey, cert, TspAlgorithms.MD5, "1.2");

            tsTokenGen.SetCertificates(certs);

            tsTokenGen.SetAccuracySeconds(1);
            tsTokenGen.SetAccuracyMillis(2);
            tsTokenGen.SetAccuracyMicros(3);

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

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

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

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

            TimeStampToken tsToken = tsResp.TimeStampToken;

            tsToken.Validate(cert);

            //
            // check validation
            //
            tsResp.Validate(request);

            //
            // check tstInfo
            //
            TimeStampTokenInfo tstInfo = tsToken.TimeStampInfo;

            //
            // check accuracy
            //
            GenTimeAccuracy accuracy = tstInfo.GenTimeAccuracy;

            Assert.AreEqual(1, accuracy.Seconds);
            Assert.AreEqual(2, accuracy.Millis);
            Assert.AreEqual(3, accuracy.Micros);

            Assert.AreEqual(BigInteger.ValueOf(23), tstInfo.SerialNumber);

            Assert.AreEqual("1.2", tstInfo.Policy);

            //
            // test certReq
            //
            IX509Store store = tsToken.GetCertificates("Collection");

            ICollection certificates = store.GetMatches(null);

            Assert.AreEqual(0, certificates.Count);
        }
Ejemplo n.º 15
0
        public void TestNoNonce()
        {
            TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator(
                privateKey, cert, TspAlgorithms.MD5, "1.2.3");

            tsTokenGen.SetCertificates(certs);

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

            Assert.IsFalse(request.CertReq);

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

            TimeStampResponse tsResp = tsRespGen.Generate(request, BigInteger.ValueOf(24), DateTime.UtcNow);

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

            TimeStampToken tsToken = tsResp.TimeStampToken;

            tsToken.Validate(cert);

            //
            // check validation
            //
            tsResp.Validate(request);

            //
            // check tstInfo
            //
            TimeStampTokenInfo tstInfo = tsToken.TimeStampInfo;

            //
            // check accuracy
            //
            GenTimeAccuracy accuracy = tstInfo.GenTimeAccuracy;

            Assert.IsNull(accuracy);

            Assert.AreEqual(BigInteger.ValueOf(24), tstInfo.SerialNumber);

            Assert.AreEqual("1.2.3", tstInfo.Policy);

            Assert.IsFalse(tstInfo.IsOrdered);

            Assert.IsNull(tstInfo.Nonce);

            //
            // test certReq
            //
            IX509Store store = tsToken.GetCertificates("Collection");

            ICollection certificates = store.GetMatches(null);

            Assert.AreEqual(0, certificates.Count);
        }
Ejemplo n.º 16
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);
        }
        private void testNoNonse(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs)
        {
            TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator(
                privateKey, cert, TspAlgorithms.MD5, "1.2.3");

            tsTokenGen.SetCertificates(certs);

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

            ArrayList algorithms = new ArrayList();

            algorithms.Add(TspAlgorithms.Sha1);

            request.Validate(algorithms, new ArrayList(), new ArrayList());

            Assert.False(request.CertReq);

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

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

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

            TimeStampToken tsToken = tsResp.TimeStampToken;

            tsToken.Validate(cert);

            tsResp.Validate(request);

            TimeStampTokenInfo tstInfo = tsToken.TimeStampInfo;

            GenTimeAccuracy accuracy = tstInfo.GenTimeAccuracy;

            Assert.IsNull(accuracy);

            Assert.IsTrue(new BigInteger("24").Equals(tstInfo.SerialNumber));


            Assert.IsTrue("1.2.3" == tstInfo.Policy);

            Assert.False(tstInfo.IsOrdered);

            Assert.IsNull(tstInfo.Nonce);

            //
            // test certReq
            //
            IX509Store store = tsToken.GetCertificates();

            ICollection certificates = store.GetMatches(null);

            Assert.IsTrue(0 == certificates.Count);
        }
Ejemplo n.º 18
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));
        }
Ejemplo n.º 19
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
        }
        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);
        }
Ejemplo 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());
        }
Ejemplo n.º 22
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);
        }
Ejemplo n.º 23
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());
            }
        }
Ejemplo n.º 25
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
            }
        }
Ejemplo n.º 26
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);
        }
Ejemplo n.º 27
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 TimeStampResponse GetSignedHashFromTsa(byte[] hash)
        {
            /*
             * if(!CheckIfUrlReachable(stampURI))
             * {
             *  return null;
             * }
             */

            TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator();
            // Dummy request
            TimeStampRequest request = reqGen.Generate(
                TspAlgorithms.Sha1,
                hash,
                BigInteger.ValueOf(100)
                );

            byte[] reqData = request.GetEncoded();

            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(stampURI);

            httpReq.Method        = "POST";
            httpReq.ContentType   = "application/timestamp-query";
            httpReq.ContentLength = reqData.Length;

            //Configure Timeout
            //httpReq.Timeout = 5000;
            //httpReq.ReadWriteTimeout = 32000;


            // Write the request content
            Stream reqStream = httpReq.GetRequestStream();

            reqStream.Write(reqData, 0, reqData.Length);
            reqStream.Close();

            HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();

            // Read the response
            Stream            respStream = new BufferedStream(httpResp.GetResponseStream());
            TimeStampResponse response   = new TimeStampResponse(respStream);

            respStream.Close();

            return(response);
        }
Ejemplo n.º 29
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.");
            }
        }
        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.");
            }
        }
Ejemplo n.º 31
0
		public void TestBasic()
		{
			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[20], BigInteger.ValueOf(100));

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

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

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

			TimeStampToken  tsToken = tsResp.TimeStampToken;

			tsToken.Validate(cert);

			AttributeTable table = tsToken.SignedAttributes;

			Assert.IsNotNull(table[PkcsObjectIdentifiers.IdAASigningCertificate], "no signingCertificate attribute found");
		}
Ejemplo n.º 32
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.");
			}
		}
Ejemplo n.º 33
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.");
			}
		}
Ejemplo n.º 34
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.");
			}
		}
Ejemplo n.º 35
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.");
			}
		}
Ejemplo n.º 36
0
		public void TestTokenEncoding()
		{
			TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator(
				privateKey, cert, TspAlgorithms.Sha1, "1.2.3.4.5.6");

			tsTokenGen.SetCertificates(certs);

			TimeStampRequestGenerator  reqGen = new TimeStampRequestGenerator();
			TimeStampRequest           request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20], BigInteger.ValueOf(100));
			TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed);
			TimeStampResponse          tsResp = tsRespGen.Generate(request, BigInteger.ValueOf(23), DateTime.UtcNow);

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

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

			if (!Arrays.AreEqual(tsResponse.GetEncoded(), tsResp.GetEncoded())
				|| !Arrays.AreEqual(tsResponse.TimeStampToken.GetEncoded(),
							tsResp.TimeStampToken.GetEncoded()))
			{
				Assert.Fail();
			}
		}
Ejemplo n.º 37
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);
		}
Ejemplo n.º 38
0
		public void TestNoNonce()
		{
			TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator(
				privateKey, cert, TspAlgorithms.MD5, "1.2.3");

			tsTokenGen.SetCertificates(certs);

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

			Assert.IsFalse(request.CertReq);

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

			TimeStampResponse tsResp = tsRespGen.Generate(request, BigInteger.ValueOf(24), DateTime.UtcNow);

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

			TimeStampToken tsToken = tsResp.TimeStampToken;

			tsToken.Validate(cert);

			//
			// check validation
			//
			tsResp.Validate(request);

			//
			// check tstInfo
			//
			TimeStampTokenInfo tstInfo = tsToken.TimeStampInfo;

			//
			// check accuracy
			//
			GenTimeAccuracy accuracy = tstInfo.GenTimeAccuracy;

			Assert.IsNull(accuracy);

			Assert.AreEqual(BigInteger.ValueOf(24), tstInfo.SerialNumber);

			Assert.AreEqual("1.2.3", tstInfo.Policy);

			Assert.IsFalse(tstInfo.IsOrdered);

			Assert.IsNull(tstInfo.Nonce);

			//
			// test certReq
			//
			IX509Store store = tsToken.GetCertificates("Collection");

			ICollection certificates = store.GetMatches(null);

			Assert.AreEqual(0, certificates.Count);
		}
Ejemplo n.º 39
0
		public void TestResponseValidation()
		{
			TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator(
				privateKey, cert, TspAlgorithms.MD5, "1.2");

			tsTokenGen.SetCertificates(certs);

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

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

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

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

			TimeStampToken tsToken = tsResp.TimeStampToken;

			tsToken.Validate(cert);

			//
			// check validation
			//
			tsResp.Validate(request);

			try
			{
				request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20], BigInteger.ValueOf(101));

				tsResp.Validate(request);

				Assert.Fail("response validation failed on invalid nonce.");
			}
			catch (TspValidationException)
			{
				// ignore
			}

			try
			{
				request = reqGen.Generate(TspAlgorithms.Sha1, new byte[22], BigInteger.ValueOf(100));

				tsResp.Validate(request);

				Assert.Fail("response validation failed on wrong digest.");
			}
			catch (TspValidationException)
			{
				// ignore
			}

			try
			{
				request = reqGen.Generate(TspAlgorithms.MD5, new byte[20], BigInteger.ValueOf(100));

				tsResp.Validate(request);

				Assert.Fail("response validation failed on wrong digest.");
			}
			catch (TspValidationException)
			{
				// ignore
			}
		}