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();
            }
        }
Beispiel #2
0
        public static byte[] GetTimestampForOutput(TimeStampResponse response, OutputFormat outputFormat, TimestampData timestampData)
        {
            switch (outputFormat)
            {
            case OutputFormat.TSR:
                return(response.GetEncoded());

            case OutputFormat.ASICS:
                return(Utils.GetAsics(response.GetEncoded(), timestampData.GetRawData(), timestampData.HasMultipleFiles()));
            }
            return(null);
        }
        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.");
            }
        }
Beispiel #4
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);
        }
        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");
        }
Beispiel #6
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.");
            }
        }
        internal string GetSignedHashFromTsa(XmlDocument xmlDxocument)
        {
            byte[]            hash = GetXmlHashByteStream(xmlDxocument);
            TimeStampResponse timeStampResponse = GetSignedHashFromTsa(hash);

            byte[] signedEncodedByteStream = timeStampResponse.GetEncoded();
            return(Convert.ToBase64String(signedEncodedByteStream));
        }
Beispiel #9
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);
        }
Beispiel #10
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);
        }
        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);
        }
Beispiel #12
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);
        }
Beispiel #14
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.");
            }
        }
Beispiel #15
0
        private void basicSha256Test(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs)
        {
            var sInfoGenerator = makeInfoGenerator(privateKey, cert, TspAlgorithms.Sha256, null, null);
            TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator(
                sInfoGenerator,
                Asn1DigestFactory.Get(NistObjectIdentifiers.IdSha256), new DerObjectIdentifier("1.2"), true);


            tsTokenGen.SetCertificates(certs);

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

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

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

            Assert.AreEqual((int)PkiStatus.Granted, tsResp.Status);

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

            TimeStampToken tsToken = tsResp.TimeStampToken;

            tsToken.Validate(cert);

            Asn1.Cms.AttributeTable table = tsToken.SignedAttributes;

            Assert.NotNull(table[PkcsObjectIdentifiers.IdAASigningCertificateV2]);

            Asn1DigestFactory digCalc = Asn1DigestFactory.Get(NistObjectIdentifiers.IdSha256);
            IStreamCalculator calc    = digCalc.CreateCalculator();

            using (Stream s = calc.Stream)
            {
                var crt = cert.GetEncoded();
                s.Write(crt, 0, crt.Length);
            }

            byte[] certHash = ((SimpleBlockResult)calc.GetResult()).Collect();

            SigningCertificateV2 sigCertV2 = SigningCertificateV2.GetInstance(table[PkcsObjectIdentifiers.IdAASigningCertificateV2].AttrValues[0]);

            Assert.IsTrue(Arrays.AreEqual(certHash, sigCertV2.GetCerts()[0].GetCertHash()));
        }
        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 void certReqTest(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs)
        {
            TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator(
                privateKey, cert, TspAlgorithms.MD5, "1.2");

            tsTokenGen.SetCertificates(certs);


            TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator();

            reqGen.SetCertReq(false);

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

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

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

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

            TimeStampToken tsToken = tsResp.TimeStampToken;

            Assert.IsNull(tsToken.TimeStampInfo.GenTimeAccuracy);              // check for abscence of accuracy

            Assert.True("1.2".Equals(tsToken.TimeStampInfo.Policy));

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

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

            if (certsColl.Count > 0)
            {
                Assert.Fail("certReq(false) found certificates in response.");
            }
        }
        private byte[] RFC3161(byte[] bRequest, DateTime signTime, BigInteger biSerial)
        {
            TimeStampRequest timeStampRequest = new TimeStampRequest(bRequest);

            Asn1EncodableVector signedAttributes = new Asn1EncodableVector();

            signedAttributes.Add(new Attribute(CmsAttributes.ContentType, new DerSet(new DerObjectIdentifier("1.2.840.113549.1.7.1"))));
            signedAttributes.Add(new Attribute(CmsAttributes.SigningTime, new DerSet(new DerUtcTime(signTime))));
            AttributeTable signedAttributesTable = new AttributeTable(signedAttributes);

            signedAttributesTable.ToAsn1EncodableVector();

            TimeStampTokenGenerator timeStampTokenGenerator = new TimeStampTokenGenerator(priKey, x509Cert, new DefaultDigestAlgorithmIdentifierFinder().find(hashAlg).Algorithm.Id, "1.3.6.1.4.1.13762.3", signedAttributesTable, null);

            timeStampTokenGenerator.SetCertificates(x509Store);
            TimeStampResponseGenerator timeStampResponseGenerator = new TimeStampResponseGenerator(timeStampTokenGenerator, TspAlgorithms.Allowed);
            TimeStampResponse          timeStampResponse          = timeStampResponseGenerator.Generate(timeStampRequest, biSerial, signTime);

            byte[] result = timeStampResponse.GetEncoded();
            return(result);
        }
        private void resolutionTest(AsymmetricKeyParameter privateKey, X509.X509Certificate cert, IX509Store certs, Resolution resoution, string timeString)
        {
            TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator(
                privateKey, cert, TspAlgorithms.Sha1, "1.2");

            tsTokenGen.Resolution = resoution;
            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), UnixEpoch.AddMilliseconds(9999));

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

            TimeStampToken tsToken = tsResp.TimeStampToken;

            // This done instead of relying on string comparison.
            Assert.AreEqual(timeString, tsToken.TimeStampInfo.TstInfo.GenTime.TimeString);

            tsResp  = tsRespGen.Generate(request, new BigInteger("23"), UnixEpoch.AddMilliseconds(9000));
            tsToken = tsResp.TimeStampToken;
            Assert.AreEqual("19700101000009Z", tsToken.TimeStampInfo.TstInfo.GenTime.TimeString);

            if ((int)resoution > (int)Resolution.R_HUNDREDTHS_OF_SECONDS)
            {
                tsResp  = tsRespGen.Generate(request, new BigInteger("23"), UnixEpoch.AddMilliseconds(9990));
                tsToken = tsResp.TimeStampToken;
                Assert.AreEqual("19700101000009.99Z", tsToken.TimeStampInfo.TstInfo.GenTime.TimeString);
            }

            if ((int)resoution > (int)Resolution.R_TENTHS_OF_SECONDS)
            {
                tsResp  = tsRespGen.Generate(request, new BigInteger("23"), UnixEpoch.AddMilliseconds(9900));
                tsToken = tsResp.TimeStampToken;
                Assert.AreEqual("19700101000009.9Z", tsToken.TimeStampInfo.TstInfo.GenTime.TimeString);
            }
        }
Beispiel #20
0
        public void TestBasicSha256()
        {
            var sInfoGenerator = makeInfoGenerator(privateKey, cert, TspAlgorithms.Sha256, null, null);
            TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator(
                sInfoGenerator,
                Asn1DigestFactory.Get(NistObjectIdentifiers.IdSha256), new DerObjectIdentifier("1.2"), true);


            tsTokenGen.SetCertificates(certs);

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

            Assert.IsFalse(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);

            TimeStampTokenInfo tstInfo = tsToken.TimeStampInfo;

            AttributeTable table = tsToken.SignedAttributes;

            var r = table.Get(PkcsObjectIdentifiers.IdAASigningCertificateV2);

            Assert.NotNull(r);
            Assert.AreEqual(PkcsObjectIdentifiers.IdAASigningCertificateV2, r.AttrType);
            var set = r.AttrValues;
            SigningCertificateV2 sCert = SigningCertificateV2.GetInstance(set[0]);

            var issSerNum = sCert.GetCerts()[0].IssuerSerial;

            Assert.AreEqual(cert.SerialNumber, issSerNum.Serial.Value);
        }
        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.");
            }
        }
        private void additionalExtensionTest(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);

            X509ExtensionsGenerator extensionsGenerator = new X509ExtensionsGenerator();

            extensionsGenerator.AddExtension(X509Extensions.AuditIdentity, false, new DerUtf8String("Test"));


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

            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");

            X509Extensions ext = tsToken.TimeStampInfo.TstInfo.Extensions;

            Assert.True(1 == ext.GetExtensionOids().Length);

            X509Extension left = new X509Extension(DerBoolean.False, new DerOctetString(new DerUtf8String("Test").GetEncoded()));

            Assert.True(left.Equals(ext.GetExtension(X509Extensions.AuditIdentity)));
        }
Beispiel #23
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");
        }
Beispiel #24
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.");
            }
        }
Beispiel #25
0
    // Třída podepíše certifikátem dokument XML a přidá časové razítko
    // Pokud je již dokument podepsaný, přidá se další podpis
    public XmlDocument SignWithTimestamp(XmlDocument doc, X509Certificate2 cert, string tsURL, string tsUsername, string tsPassword)
    {
        // před podepisováním z dokumentu odstraníme komentáře (.NET s nimi má problémy pokud se kombinují s XPath transformacemi)
        XmlDocument strippedDoc = RemoveComments(doc);

        // definice mapování prefixů na jmenné prostory
        XmlNamespaceManager manager = new XmlNamespaceManager(strippedDoc.NameTable);

        manager.AddNamespace("dsig", "http://www.w3.org/2000/09/xmldsig#");

        // zjištění kolik podpisů již v dokumentu je
        int signatures = strippedDoc.SelectNodes("//dsig:Signature", manager).Count;

        string signatureID = (signatures + 1).ToString();

        // vytvoření elementu Object pro časové razítko
        XmlElement objectElement = doc.CreateElement("Object", "http://www.w3.org/2000/09/xmldsig#");

        // spočítání otisku certifikátu
        SHA256 sha256   = new SHA256Managed();
        string certHash = Convert.ToBase64String(sha256.ComputeHash(cert.GetRawCertData()));

        objectElement.InnerXml = @"<xades:QualifyingProperties xmlns:xades='http://uri.etsi.org/01903/v1.3.2#' Target='#Signature-" + signatureID + @"' xmlns='http://www.w3.org/2000/09/xmldsig#'>
                <xades:SignedProperties Id='Signature-" + signatureID + @"-SignedProperties'>
                  <xades:SignedSignatureProperties>
                    <xades:SigningTime>" + XmlConvert.ToString(DateTime.Now.ToUniversalTime(), XmlDateTimeSerializationMode.RoundtripKind) + @"</xades:SigningTime>
                    <xades:SigningCertificate>
                      <xades:Cert>
                        <xades:CertDigest>
                          <DigestMethod Algorithm='http://www.w3.org/2001/04/xmlenc#sha256'></DigestMethod>
                          <DigestValue>" + certHash + @"</DigestValue>
                        </xades:CertDigest>
                        <xades:IssuerSerial>
                          <X509IssuerName>" + cert.IssuerName + @"</X509IssuerName>
                          <X509SerialNumber>" + cert.GetSerialNumberString() + @"</X509SerialNumber>
                        </xades:IssuerSerial>
                      </xades:Cert>
                    </xades:SigningCertificate>
                  </xades:SignedSignatureProperties>
                  <xades:SignedDataObjectProperties>
                    <xades:DataObjectFormat ObjectReference='#Signature-" + signatureID + @"-Document-Reference'>
                      <xades:MimeType>application/xml</xades:MimeType>
                    </xades:DataObjectFormat>
                  </xades:SignedDataObjectProperties>
                </xades:SignedProperties>
                <xades:UnsignedProperties>
                  <xades:UnsignedSignatureProperties>
                    <xades:SignatureTimeStamp>
                      <xades:EncapsulatedTimeStamp Encoding='http://uri.etsi.org/01903/v1.2.2#DER'></xades:EncapsulatedTimeStamp>
                    </xades:SignatureTimeStamp>
                  </xades:UnsignedSignatureProperties>
                </xades:UnsignedProperties>
               </xades:QualifyingProperties>";


        // objekt sloužící pro vytvoření podpisu
        CustomIdSignedXml signedXml = new CustomIdSignedXml(strippedDoc, objectElement);

        // podepisovat budeme privátním klíčem z certifikátu
        signedXml.SigningKey = cert.PrivateKey;

        // podepisovat budeme pomocí RSA-SHA256
        signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";

        // reference na podepisovaný dokument ("" znamená celý dokument)
        Reference reference = new Reference();

        reference.Uri = "";
        reference.Id  = "Signature-" + signatureID + "-Document-Reference";

        // pro výpočet otisku se bude používat SHA-256
        reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";

        // digitální podpis bude přímo součástí dokumentu XML (tzv. "enveloped signature")
        XmlDsigEnvelopedSignatureTransform envTransform = new XmlDsigEnvelopedSignatureTransform();

        reference.AddTransform(envTransform);

        // navíc budeme používat XPath transoformaci, která dovoluje přidat několik podpisů najednou
        XmlDsigXPathTransform xpathTransform = new XmlDsigXPathTransform();

        // příprava definice XPath transformace jako struktura XML signature
        XmlDocument transformBody = new XmlDocument();

        // podoba XPath filtru se liší podle počtu podpisů
        if (signatures == 0)
        {
            transformBody.LoadXml("<dsig:XPath xmlns:dsig='http://www.w3.org/2000/09/xmldsig#'>not(ancestor-or-self::dsig:Signature)</dsig:XPath>");
        }
        else
        {
            transformBody.LoadXml("<dsig:XPath xmlns:dsig='http://www.w3.org/2000/09/xmldsig#'>not(ancestor-or-self::dsig:Signature) or not(ancestor-or-self::dsig:Signature/preceding-sibling::dsig:Signature[" + signatures + "])</dsig:XPath>");
        }

        // načtení definice XPath transformace do objektu
        xpathTransform.LoadInnerXml(transformBody.SelectNodes("/*[1]"));

        // přidání XPath transformace
        reference.AddTransform(xpathTransform);

        // přidání reference do podpisu
        signedXml.AddReference(reference);

        // reference na SignedProperties -- XAdES-BES vyžaduje podpis certifikátu
        Reference spReference = new Reference();

        spReference.Uri = "#Signature-" + signatureID + "-SignedProperties";

        // pro výpočet otisku se bude používat SHA-256
        spReference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";

        // přidání reference do podpisu
        signedXml.AddReference(spReference);

        // přidání certifikátu do podpisu
        KeyInfo keyInfo = new KeyInfo();

        keyInfo.AddClause(new KeyInfoX509Data(cert));
        signedXml.KeyInfo = keyInfo;

        // přidání objektu s časovým razítkem do podpisu
        DataObject dataObj = new DataObject();

        dataObj.LoadXml(objectElement);
        signedXml.AddObject(dataObj);

        // výpočet podpisu
        signedXml.ComputeSignature();

        // získání XML reprezentace podpisu
        XmlElement xmlSignature = signedXml.GetXml();

        // k podpisu přidáme identifikátor, tak jak doporučuje standard ISDOC
        xmlSignature.SetAttribute("Id", "Signature-" + signatureID);

        // XML dokument pro podepsaný výsledek
        XmlDocument result = new XmlDocument();

        // bílé znaky musíme zachovat, jinak se špatně spočte hash
        result.PreserveWhitespace = true;

        // načtení původního dokumentu
        result.AppendChild(result.ImportNode(strippedDoc.DocumentElement, true));

        // připojení podpisu na konec dokumentu XML
        result.DocumentElement.AppendChild(result.ImportNode(xmlSignature, true));

        // Spočítání otisku digitálního podpisu
        byte[] digest;
        digest = sha256.ComputeHash(signedXml.SignatureValue);

        // generátor požadavků na časové razítko
        TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator();

        // vytvoření dat pro požadavek na timestamp server
        TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha256, digest);

        // získání surových dat pro poslání na timestamp server
        byte[] reqData = request.GetEncoded();

        // inicializace požadavku na timestamp server
        HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(tsURL);

        httpReq.Method        = "POST";
        httpReq.ContentType   = "application/timestamp-query";
        httpReq.ContentLength = reqData.Length;
        httpReq.Credentials   = new NetworkCredential(tsUsername, tsPassword);

        // odeslání požadavku na timestamp server
        Stream reqStream = httpReq.GetRequestStream();

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

        // přečtení odpovědi
        HttpWebResponse   httpResp   = (HttpWebResponse)httpReq.GetResponse();
        Stream            respStream = new BufferedStream(httpResp.GetResponseStream());
        TimeStampResponse response   = new TimeStampResponse(respStream);

        respStream.Close();

        // Console.WriteLine("Status razítkování: " + response.Status);
        // Console.WriteLine("Čas razítka: " + response.TimeStampToken.TimeStampInfo.GenTime.ToLocalTime());
        string timestamp = Convert.ToBase64String(response.GetEncoded());

        // doplnění získaného časového razítka do dokumentu
        XmlNamespaceManager nsmng = new XmlNamespaceManager(result.NameTable);

        nsmng.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
        nsmng.AddNamespace("xades", "http://uri.etsi.org/01903/v1.3.2#");
        XmlElement etsElement = (XmlElement)result.SelectSingleNode("//*[@Id = 'Signature-" + signatureID + "']/ds:Object/xades:QualifyingProperties/xades:UnsignedProperties/xades:UnsignedSignatureProperties/xades:SignatureTimeStamp/xades:EncapsulatedTimeStamp", nsmng);

        etsElement.InnerText = timestamp;

        return(result);
    }
Beispiel #26
0
        private byte[] ParseRfc3161ResponseBody(byte[] rspBody, TimeStampRequest tspr)
        {
            TimeStampResponse tsResponse = new TimeStampResponse(rspBody);

            trace.TraceData(TraceEventType.Verbose, 0, "retrieved time-stamp response", address.ToString(), Convert.ToBase64String(tsResponse.GetEncoded()));

            try
            {
                tsResponse.Validate(tspr);
            }
            catch (Exception e)
            {
                trace.TraceEvent(TraceEventType.Error, 0, "The time-stamp response does not correspond with the request: {0}", e.Message);
                throw e;
            }

            return(tsResponse.TimeStampToken.GetEncoded());
        }
        private void overrideAttrsTest(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs)
        {
            SignerInfoGeneratorBuilder signerInfoGenBuilder = new SignerInfoGeneratorBuilder();

            IssuerSerial issuerSerial = new IssuerSerial(
                new GeneralNames(
                    new GeneralName(
                        X509CertificateStructure.GetInstance(cert.GetEncoded()).Issuer)),
                new DerInteger(cert.SerialNumber));

            byte[] certHash256;
            byte[] certHash;

            {
                Asn1DigestFactory digCalc = Asn1DigestFactory.Get(OiwObjectIdentifiers.IdSha1);
                IStreamCalculator calc    = digCalc.CreateCalculator();
                using (Stream s = calc.Stream)
                {
                    byte[] crt = cert.GetEncoded();
                    s.Write(crt, 0, crt.Length);
                }

                certHash = ((SimpleBlockResult)calc.GetResult()).Collect();
            }


            {
                Asn1DigestFactory digCalc = Asn1DigestFactory.Get(NistObjectIdentifiers.IdSha256);
                IStreamCalculator calc    = digCalc.CreateCalculator();
                using (Stream s = calc.Stream)
                {
                    byte[] crt = cert.GetEncoded();
                    s.Write(crt, 0, crt.Length);
                }

                certHash256 = ((SimpleBlockResult)calc.GetResult()).Collect();
            }


            EssCertID   essCertID   = new EssCertID(certHash, issuerSerial);
            EssCertIDv2 essCertIDv2 = new EssCertIDv2(certHash256, issuerSerial);

            signerInfoGenBuilder.WithSignedAttributeGenerator(new TestAttrGen(essCertID, essCertIDv2));


            Asn1SignatureFactory sigfact             = new Asn1SignatureFactory("SHA1WithRSA", privateKey);
            SignerInfoGenerator  signerInfoGenerator = signerInfoGenBuilder.Build(sigfact, cert);

            TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator(signerInfoGenerator,
                                                                             Asn1DigestFactory.Get(OiwObjectIdentifiers.IdSha1), new DerObjectIdentifier("1.2"), true);

            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);

            Asn1.Cms.AttributeTable table = tsToken.SignedAttributes;

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

            SigningCertificate sigCert = SigningCertificate.GetInstance(table[PkcsObjectIdentifiers.IdAASigningCertificate].AttrValues[0]);

            Assert.IsTrue(cert.CertificateStructure.Issuer.Equals(sigCert.GetCerts()[0].IssuerSerial.Issuer.GetNames()[0].Name));
            Assert.IsTrue(cert.CertificateStructure.SerialNumber.Value.Equals(sigCert.GetCerts()[0].IssuerSerial.Serial.Value));
            Assert.IsTrue(Arrays.AreEqual(certHash, sigCert.GetCerts()[0].GetCertHash()));

            SigningCertificate sigCertV2 = SigningCertificate.GetInstance(table[PkcsObjectIdentifiers.IdAASigningCertificateV2].AttrValues[0]);

            Assert.IsTrue(cert.CertificateStructure.Issuer.Equals(sigCertV2.GetCerts()[0].IssuerSerial.Issuer.GetNames()[0].Name));
            Assert.IsTrue(cert.CertificateStructure.SerialNumber.Value.Equals(sigCertV2.GetCerts()[0].IssuerSerial.Serial.Value));
            Assert.IsTrue(Arrays.AreEqual(certHash256, sigCertV2.GetCerts()[0].GetCertHash()));
        }
Beispiel #28
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
            }
        }
Beispiel #29
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();
			}
		}
Beispiel #30
0
        /// <summary>
        /// Questo metodo verifica se l'associazione fra marca e file è valida, verifica inoltre la
        /// validità del certificato firmatario della marca e la data di scadenza della marca; infine
        /// restituisce (se le verifiche vanno a buon fine) tutti i dati contenuti nella marca.
        /// </summary>
        /// <param name="tsRes"></param>
        /// <param name="tsReq"></param>
        /// <returns></returns>
        protected OutputResponseMarca checkMarca(TimeStampResponse tsRes, TimeStampRequest tsReq)
        {
            OutputResponseMarca outTSR = new OutputResponseMarca();

            try
            {
                tsRes.Validate(tsReq);
                outTSR.esito             = "OK";
                outTSR.descrizioneErrore = string.Empty;
            }
            catch (TspException e)
            {
                outTSR.esito             = "KO";
                outTSR.descrizioneErrore = "verifica della marca fallita: " + e.Message;
                logger.Debug("verifica della marca fallita: " + e.Message);
                //return outTSR;
            }

            TimeStampToken tsToken = tsRes.TimeStampToken;

            //Verifica data scadenza marca secondo l'ora locale
            Org.BouncyCastle.X509.Store.IX509Store store = tsToken.GetCertificates("Collection");
            Org.BouncyCastle.X509.X509Certificate  cert  = (Org.BouncyCastle.X509.X509Certificate) new ArrayList(store.GetMatches(tsToken.SignerID))[0];
            //se la data attuale è maggiore di quella di scadenza del certificato che ha firmato la marca
            //allora la marca è scaduta!!!
            if (DateTime.Now.CompareTo(cert.NotAfter.ToLocalTime()) > 0)
            {
                //outTSR.esito = "KO";
                outTSR.descrizioneErrore = "marca temporale scaduta";
                logger.Debug("marca temporale scaduta");
                //return outTSR;
            }

            try
            {
                //estrazione delle informazioni dalla marca
                outTSR.dsm            = cert.NotAfter.ToLocalTime().ToString();
                outTSR.sernum         = tsToken.TimeStampInfo.SerialNumber.ToString();
                outTSR.fhash          = byteArrayToHexa(tsToken.TimeStampInfo.TstInfo.MessageImprint.GetHashedMessage());
                outTSR.docm           = tsToken.TimeStampInfo.TstInfo.GenTime.TimeString;
                outTSR.docm_date      = tsToken.TimeStampInfo.GenTime.ToLocalTime().ToString();
                outTSR.marca          = Convert.ToBase64String(tsRes.GetEncoded());
                outTSR.algCertificato = cert.SigAlgName;
                outTSR.fromDate       = cert.NotBefore.ToLocalTime().ToString();
                outTSR.snCertificato  = cert.SerialNumber.ToString();
                //Algoritmo hash utilizzato per l'impronta
                string algHashOid = tsToken.TimeStampInfo.MessageImprintAlgOid;
                if (!string.IsNullOrEmpty(algHashOid))
                {
                    System.Security.Cryptography.Oid oidHash = new System.Security.Cryptography.Oid(algHashOid);
                    outTSR.algHash = oidHash.FriendlyName;
                }

                outTSR.TSA = new TSARFC2253();

                //Con le TSA di test potrebbe non essere valorizzato l'oggetto TSA
                logger.Debug("Controllo TSA : " + tsToken.TimeStampInfo.Tsa);
                try
                {
                    if (tsToken.TimeStampInfo.Tsa != null)
                    {
                        string oid      = string.Empty;
                        string oidValue = string.Empty;
                        logger.Debug("TagNo: " + tsToken.TimeStampInfo.Tsa.TagNo);
                        for (int n = 0; n < tsToken.TimeStampInfo.Tsa.TagNo; n++)
                        {
                            logger.Debug("Tag: " + n);
                            Org.BouncyCastle.Asn1.Asn1Sequence seq = (Org.BouncyCastle.Asn1.Asn1Sequence)tsToken.TimeStampInfo.Tsa.Name.ToAsn1Object();

                            //Obsoleto
                            //Org.BouncyCastle.Asn1.Asn1Object obj = (Org.BouncyCastle.Asn1.Asn1Object)seq.GetObjectAt(n);
                            Org.BouncyCastle.Asn1.Asn1Object obj = (Org.BouncyCastle.Asn1.Asn1Object)seq[n];

                            Org.BouncyCastle.Asn1.Asn1Set set1 = (Org.BouncyCastle.Asn1.Asn1Set)obj.ToAsn1Object();

                            //Obsoleto
                            //seq = (Org.BouncyCastle.Asn1.Asn1Sequence)set1.GetObjectAt(0);
                            //obj = (Org.BouncyCastle.Asn1.Asn1Object)seq.GetObjectAt(0);
                            seq = (Org.BouncyCastle.Asn1.Asn1Sequence)set1[0];
                            obj = (Org.BouncyCastle.Asn1.Asn1Object)seq[0];


                            oid = obj.ToString();

                            //Obsoleto
                            //obj = (Org.BouncyCastle.Asn1.Asn1Object)seq.GetObjectAt(1);
                            obj = (Org.BouncyCastle.Asn1.Asn1Object)seq[1];

                            oidValue = obj.ToString();
                            System.Security.Cryptography.Oid oid_obj = new System.Security.Cryptography.Oid(oid);
                            string friendly = oid_obj.FriendlyName;
                            logger.Debug("oid: " + oid + " friendly: " + friendly);
                            switch (friendly)
                            {
                            case "CN":
                                outTSR.TSA.CN = oidValue;
                                break;

                            case "OU":
                                outTSR.TSA.OU = oidValue;
                                break;

                            case "O":
                                outTSR.TSA.O = oidValue;
                                break;

                            case "C":
                                outTSR.TSA.C = oidValue;
                                break;
                            }
                        }
                        outTSR.TSA.TSARFC2253Name = "CN=" + outTSR.TSA.CN + ",OU=" + outTSR.TSA.OU + ",O=" + outTSR.TSA.O + ",C=" + outTSR.TSA.C;
                    }
                }
                catch (Exception e)
                {
                    logger.Debug("Eccezione controllo TSA : " + e.Message);
                }
                logger.Debug("Fine Controllo TSA");
            }
            catch (Exception eTsp)
            {
                outTSR.esito             = "KO";
                outTSR.descrizioneErrore = "estrazione delle informazioni dalla marca fallita: " + eTsp.Message;
                logger.Debug("estrazione delle informazioni dalla marca fallita: " + eTsp.Message);
                //return outTSR;
            }

            //verifico l'esistenza del documento al quale è associata la marca temporale
            //Commentata perchè l'impronta del documento è ancora calcolata con SHA1 invece che SHA256
            //DocsPaDB.Query_DocsPAWS.Documenti documento = new DocsPaDB.Query_DocsPAWS.Documenti();
            //outTSR.timestampedDoc = documento.GetDocNumberByImpronta(outTSR.fhash);
            //if (string.IsNullOrEmpty(outTSR.timestampedDoc))
            //{
            //    outTSR.timestampedDoc = "Non esiste alcun documento associato alla marca temporale.";
            //}

            //costruisco l'oggetto rappresentante il contenuto in chiaro della marca
            outTSR.DecryptedTSR             = new Marca();
            outTSR.DecryptedTSR.content     = contentMarca(outTSR);
            outTSR.DecryptedTSR.contentType = "text/html"; //"application/x-html";
            outTSR.DecryptedTSR.length      = outTSR.DecryptedTSR.content.Length;

            return(outTSR);
        }
        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");
        }