Ejemplo n.º 1
0
        public static IList GetCrlsFromStore(
			IX509Store crlStore)
        {
            try
            {
                IList crls = new ArrayList();

                if (crlStore != null)
                {
                    foreach (X509Crl c in crlStore.GetMatches(null))
                    {
                        crls.Add(
                            CertificateList.GetInstance(
                                Asn1Object.FromByteArray(c.GetEncoded())));
                    }
                }

                return crls;
            }
            catch (CrlException e)
            {
                throw new CmsException("error encoding crls", e);
            }
            catch (Exception e)
            {
                throw new CmsException("error processing crls", e);
            }
        }
Ejemplo n.º 2
0
        private static X509Certificate GetCertificate(SignerInformation signer, IX509Store cmsCertificates)
        {
            X509Certificate cert = null;

            // Create a selector with the information necessary to
            // find the signer certificate
            X509CertStoreSelector sel = new X509CertStoreSelector();
            sel.Issuer = signer.SignerID.Issuer;
            sel.SerialNumber = signer.SignerID.SerialNumber;

            // Try find a match
            IList certificatesFound = new ArrayList( cmsCertificates.GetMatches(sel) );

            if (certificatesFound.Count > 0) // Match found
            {
                // Load certificate from CMS

                Console.WriteLine("Loading signer's certificate from CMS...");

                cert = (X509Certificate)certificatesFound[0];
            }
            else
            {
                // Load certificate from file

                Console.WriteLine("Loading signer's certificate from file...");

                ReadCertificate("..\\..\\example.cer");
            }
            return cert;
        }
Ejemplo n.º 3
0
		public static IList GetCertificatesFromStore(
			IX509Store certStore)
		{
			try
			{
				IList certs = Platform.CreateArrayList();

				if (certStore != null)
				{
					foreach (X509Certificate c in certStore.GetMatches(null))
					{
						certs.Add(
							X509CertificateStructure.GetInstance(
								Asn1Object.FromByteArray(c.GetEncoded())));
					}
				}

				return certs;
			}
			catch (CertificateEncodingException e)
			{
				throw new CmsException("error encoding certs", e);
			}
			catch (Exception e)
			{
				throw new CmsException("error processing certs", e);
			}
		}
Ejemplo n.º 4
0
        internal TripleUnwrapper(Level? level, ITimemarkProvider timemarkauthority, X509Certificate2Collection encCerts)
        {
            if (level == Level.L_Level || level == Level.A_level ) throw new ArgumentException("level", "Only null or levels B, T, LT and LTA are allowed");

            this.level = level;
            this.timemarkauthority = timemarkauthority;
            //Wrap it inside a IX509Store to (incorrectly) returns an windows x509Certificate2
            encCertStore = encCerts == null || encCerts.Count == 0 ? null : new WinX509CollectionStore(encCerts);
        }
Ejemplo n.º 5
0
        public static CertificateSecurityInformation VerifyAuth(Org.BouncyCastle.X509.X509Certificate cert, DateTime date, IX509Store certs, IList<CertificateList> crls, IList<BasicOcspResponse> ocsps, bool checkRevocation, bool checkTime)
        {
            CertificateSecurityInformation result = Verify(cert, date, certs, crls, ocsps, checkRevocation, checkTime);

            if (!cert.GetKeyUsage()[0])
            {
                result.securityViolations.Add(CertSecurityViolation.NotValidForUsage);
                trace.TraceEvent(TraceEventType.Warning, 0, "The key usage did not have the correct usage flag set");
            }

            return result;
        }
Ejemplo n.º 6
0
		static TspTest()
		{
			string signDN = "O=Bouncy Castle, C=AU";
			AsymmetricCipherKeyPair signKP = TspTestUtil.MakeKeyPair();
			X509Certificate signCert = TspTestUtil.MakeCACertificate(signKP, signDN, signKP, signDN);

			string origDN = "CN=Eric H. Echidna, [email protected], O=Bouncy Castle, C=AU";
			AsymmetricCipherKeyPair origKP = TspTestUtil.MakeKeyPair();
			privateKey = origKP.Private;

			cert = TspTestUtil.MakeCertificate(origKP, origDN, signKP, signDN);

			IList certList = new ArrayList();
			certList.Add(cert);
			certList.Add(signCert);

			certs = X509StoreFactory.Create(
				"Certificate/Collection",
				new X509CollectionStoreParameters(certList));
		}
Ejemplo n.º 7
0
		private void MakeCertStore(string[] _strs, out IX509Store certStore, out IX509Store crlStore)
		{
			ArrayList certs = new ArrayList();
			ArrayList crls = new ArrayList();
			crls.Add(trustedCRL);

			for (int i = 0; i < _strs.Length; i++)
			{
				if (_strs[i].StartsWith("MIIC"))
				{
					certs.Add(certParser.ReadCertificate(Base64.Decode(_strs[i])));
				}
				else if (_strs[i].StartsWith("MIIB"))
				{
					crls.Add(crlParser.ReadCrl(Base64.Decode(_strs[i])));
				}
				else
				{
					throw new ArgumentException("Invalid certificate or crl");
				}
			}

			// Insert elements backwards to muck up forward ordering dependency
//            IList _vec2 = new ArrayList();
//            for (int i = _vec.Count - 1; i >= 0; i--)
//            {
//                _vec2.Add(_vec[i]);
//            }
			certs.Reverse();
			crls.Reverse();

			certStore = X509StoreFactory.Create("Certificate/Collection",
				new X509CollectionStoreParameters(certs));
			crlStore = X509StoreFactory.Create("CRL/Collection",
				new X509CollectionStoreParameters(crls));
		}
Ejemplo n.º 8
0
        private static CertificateSecurityInformation Verify(Org.BouncyCastle.X509.X509Certificate cert, DateTime date, IX509Store certs, IList<CertificateList> crls, IList<BasicOcspResponse> ocsps, bool checkRevocation, bool checkTime)
        {
            CertificateSecurityInformation result = new CertificateSecurityInformation();

            AsymmetricKeyParameter key = cert.GetPublicKey();

            //check key type
            if (!(key is RsaKeyParameters))
            {
                result.securityViolations.Add(CertSecurityViolation.NotValidKeyType);
                trace.TraceEvent(TraceEventType.Warning, 0, "The key should be RSA but was {0}", key.GetType());
            }

            //check key size
            if (!VerifyKeySize(key, EteeActiveConfig.Unseal.MinimumSignatureKeySize))
            {
                result.securityViolations.Add(CertSecurityViolation.NotValidKeySize);
                trace.TraceEvent(TraceEventType.Warning, 0, "The key was smaller then {0}", EteeActiveConfig.Unseal.MinimumSignatureKeySize);
            }

            X509Certificate2Collection extraStore = new X509Certificate2Collection();
            foreach (Org.BouncyCastle.X509.X509Certificate obj in certs.GetMatches(null))
            {
                extraStore.Add(new X509Certificate2(obj.GetEncoded()));
            }
            Chain chain;
            if (checkRevocation)
                chain = new X509Certificate2(cert.GetEncoded()).BuildChain(date, extraStore, ref crls, ref ocsps, checkTime ? DateTime.UtcNow : date);
            else
                chain = new X509Certificate2(cert.GetEncoded()).BuildBasicChain(date, extraStore);

            CertificateSecurityInformation dest = null;
            foreach (ChainElement ce in chain.ChainElements)
            {
                if (dest == null) {
                    dest = result;
                }
                else
                {
                    dest.IssuerInfo = new CertificateSecurityInformation();
                    dest = dest.IssuerInfo;
                }

                dest.Certificate = ce.Certificate;
                foreach (X509ChainStatus status in ce.ChainElementStatus.Where(x => x.Status != X509ChainStatusFlags.NoError))
                {
                    dest.securityViolations.Add((CertSecurityViolation)Enum.Parse(typeof(CertSecurityViolation), Enum.GetName(typeof(X509ChainStatusFlags), status.Status)));
                }
            }
            if (chain.ChainStatus.Count(x => x.Status == X509ChainStatusFlags.PartialChain) > 0)
            {
                result.securityViolations.Add(CertSecurityViolation.IssuerTrustUnknown);
            }

            trace.TraceEvent(TraceEventType.Verbose, 0, "Verified certificate {0} for date {1}", cert.SubjectDN.ToString(), date);
            return result;
        }
Ejemplo n.º 9
0
        public static CertificateSecurityInformation VerifyEnc(Org.BouncyCastle.X509.X509Certificate encCert, Org.BouncyCastle.X509.X509Certificate authCert, DateTime date, IX509Store certs, bool checkRevocation)
        {
            CertificateSecurityInformation result = new CertificateSecurityInformation();

            result.Certificate = new X509Certificate2(encCert.GetEncoded());

            //check validity
            try
            {
                encCert.CheckValidity(date);
            }
            catch (CertificateExpiredException)
            {
                result.securityViolations.Add(CertSecurityViolation.NotTimeValid);
            }
            catch (CertificateNotYetValidException)
            {
                result.securityViolations.Add(CertSecurityViolation.NotTimeValid);
            }

            //check key usage
            int[] keyUsageIndexes = new int[] { 2, 3 };
            foreach (int i in keyUsageIndexes)
            {
                if (!encCert.GetKeyUsage()[i])
                {
                    result.securityViolations.Add(CertSecurityViolation.NotValidForUsage);
                    trace.TraceEvent(TraceEventType.Warning, 0, "The key usage did not have the correct usage flag set");
                }
            }

            //check issuer/subject
            if (!encCert.IssuerDN.Equivalent(encCert.SubjectDN, false)) result.securityViolations.Add(CertSecurityViolation.HasNotPermittedNameConstraint);

            //check key size
            if (!VerifyKeySize(encCert.GetPublicKey(), EteeActiveConfig.Unseal.MinimumEncryptionKeySize.AsymmerticRecipientKey)) result.securityViolations.Add(CertSecurityViolation.NotValidKeySize);

            //check key type
            if (!(encCert.GetPublicKey() is RsaKeyParameters)) result.securityViolations.Add(CertSecurityViolation.NotValidKeyType);

            if (authCert != null)
            {
                //check signature
                try
                {
                    encCert.Verify(authCert.GetPublicKey());
                }
                catch (InvalidKeyException)
                {
                    result.securityViolations.Add(CertSecurityViolation.NotSignatureValid);
                }

                //Validate
                result.IssuerInfo = VerifyBoth(authCert, date, certs, new List<CertificateList>(0), new List<BasicOcspResponse>(0), checkRevocation, false);
            }
            else
            {
                //We assume that we have the authCert in case it's of a 3rd person, we don't care if its or own encryption cert (we only care for the validity)
            }

            return result;
        }
Ejemplo n.º 10
0
		/**
		* Add the attribute certificates contained in the passed in store to the
		* generator.
		*
		* @param store a store of Version 2 attribute certificates
		* @throws CmsException if an error occurse processing the store.
		*/
		public void AddAttributeCertificates(
			IX509Store store)
		{
			try
			{
				foreach (IX509AttributeCertificate attrCert in store.GetMatches(null))
				{
					_certs.Add(new DerTaggedObject(false, 2,
						AttributeCertificate.GetInstance(Asn1Object.FromByteArray(attrCert.GetEncoded()))));
				}
			}
			catch (Exception e)
			{
				throw new CmsException("error processing attribute certs", e);
			}
		}
Ejemplo n.º 11
0
        public static Stream ReplaceCertificatesAndCrls(Stream original, IX509Store x509Certs, IX509Store x509Crls, IX509Store x509AttrCerts, Stream outStr)
        {
            CmsSignedDataStreamGenerator cmsSignedDataStreamGenerator = new CmsSignedDataStreamGenerator();
            CmsSignedDataParser          cmsSignedDataParser          = new CmsSignedDataParser(original);

            cmsSignedDataStreamGenerator.AddDigests(cmsSignedDataParser.DigestOids);
            CmsTypedStream signedContent = cmsSignedDataParser.GetSignedContent();
            bool           flag          = signedContent != null;
            Stream         stream        = cmsSignedDataStreamGenerator.Open(outStr, cmsSignedDataParser.SignedContentType.Id, flag);

            if (flag)
            {
                Streams.PipeAll(signedContent.ContentStream, stream);
            }
            if (x509AttrCerts != null)
            {
                cmsSignedDataStreamGenerator.AddAttributeCertificates(x509AttrCerts);
            }
            if (x509Certs != null)
            {
                cmsSignedDataStreamGenerator.AddCertificates(x509Certs);
            }
            if (x509Crls != null)
            {
                cmsSignedDataStreamGenerator.AddCrls(x509Crls);
            }
            cmsSignedDataStreamGenerator.AddSigners(cmsSignedDataParser.GetSignerInfos());
            stream.Close();
            return(outStr);
        }
Ejemplo n.º 12
0
        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);
        }
 public OriginatorInfoGenerator(IX509Store origCerts)
     : this(origCerts, null)
 {
 }
Ejemplo n.º 14
0
        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.º 15
0
        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.");
            }
        }
Ejemplo n.º 16
0
        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.");
            }
        }
Ejemplo n.º 17
0
        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.º 18
0
        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.º 19
0
        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.");
            }
        }
Ejemplo n.º 20
0
        private void testAccuracyZeroCerts(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs)
        {
            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;

            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" == tstInfo.Policy);

            IX509Store store = tsToken.GetCertificates();

            ICollection certificates = store.GetMatches(null);

            Assert.IsTrue(0 == certificates.Count);
        }
Ejemplo n.º 21
0
		/**
		* Adds an additional Bouncy Castle {@link Store} to find CRLs, certificates,
		* attribute certificates or cross certificates.
		* <p>
		* You should not use this method. This method is used for adding additional
		* X.509 stores, which are used to add (remote) locations, e.g. LDAP, found
		* during X.509 object processing, e.g. in certificates or CRLs. This method
		* is used in PKIX certification path processing.
		* </p><p>
		* If <code>store</code> is <code>null</code> it is ignored.
		* </p>
		*
		* @param store The store to add.
		* @see #getStores()
		*/
		public virtual void AddAdditionalStore(
			IX509Store store)
		{
			if (store != null)
			{
				additionalStores.Add(store);
			}
		}
Ejemplo n.º 22
0
        private void responseValidationTest(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs)
        {
            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);


            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 e)
            {
                // 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 e)
            {
                // 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 e)
            {
                // ignore
            }
        }
		public void SetCrls(
			IX509Store crls)
		{
			this.x509Crls = crls;
		}
Ejemplo n.º 24
0
        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   = essCertid,
                EssCertIDv2 = 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()));
        }
Ejemplo n.º 25
0
        PkixCertPath BuildCertPath(HashSet anchors, IX509Store certificates, IX509Store crls, X509Certificate certificate, DateTime? signingTime)
        {
            var intermediate = new X509CertificateStore ();
            foreach (X509Certificate cert in certificates.GetMatches (null))
                intermediate.Add (cert);

            var selector = new X509CertStoreSelector ();
            selector.Certificate = certificate;

            var parameters = new PkixBuilderParameters (anchors, selector);
            parameters.AddStore (GetIntermediateCertificates ());
            parameters.AddStore (intermediate);

            var localCrls = GetCertificateRevocationLists ();
            parameters.AddStore (localCrls);
            parameters.AddStore (crls);

            // Note: we disable revocation unless we actually have non-empty revocation lists
            parameters.IsRevocationEnabled = localCrls.GetMatches (null).Count > 0;
            parameters.ValidityModel = PkixParameters.ChainValidityModel;

            if (signingTime.HasValue)
                parameters.Date = new DateTimeObject (signingTime.Value);

            var result = new PkixCertPathBuilder ().Build (parameters);

            return result.CertPath;
        }
Ejemplo n.º 26
0
        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)));
        }
Ejemplo n.º 27
0
		public void AddCertificates(
			IX509Store certStore)
		{
			_certs.AddRange(CmsUtilities.GetCertificatesFromStore(certStore));
		}
Ejemplo n.º 28
0
        private void basicSha256Test(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs)
        {
            SignerInfoGenerator     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)
            {
                byte[] 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()));
        }
		/**
		* return a X509Store containing CRLs, if any, contained
		* in this message.
		*
		* @param type type of store to create
		* @return a store of CRLs
		* @exception NoSuchStoreException if the store type isn't available.
		* @exception CmsException if a general exception prevents creation of the X509Store
		*/
		public IX509Store GetCrls(
			string type)
		{
			if (_crlStore == null)
			{
				PopulateCertCrlSets();

				_crlStore = Helper.CreateCrlStore(type, _crlSet);
			}

			return _crlStore;
		}
Ejemplo n.º 30
0
        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);
            }
        }
Ejemplo n.º 31
0
        private void doTestExceptions()
        {
            byte[] enc = { (byte)0, (byte)2, (byte)3, (byte)4, (byte)5 };
//			MyCertPath mc = new MyCertPath(enc);
            MemoryStream os = new MemoryStream();
            MemoryStream ins;

            byte[] arr;

            // TODO Support serialization of cert paths?
//			ObjectOutputStream oos = new ObjectOutputStream(os);
//			oos.WriteObject(mc);
//			oos.Flush();
//			oos.Close();

            try
            {
//				CertificateFactory cFac = CertificateFactory.GetInstance("X.509");
                arr = os.ToArray();
                ins = new MemoryStream(arr, false);
//				cFac.generateCertPath(ins);
                new PkixCertPath(ins);
            }
            catch (CertificateException)
            {
                // ignore okay
            }

//			CertificateFactory cf = CertificateFactory.GetInstance("X.509");
            X509CertificateParser cf = new X509CertificateParser();
            IList certCol            = new ArrayList();

            certCol.Add(cf.ReadCertificate(certA));
            certCol.Add(cf.ReadCertificate(certB));
            certCol.Add(cf.ReadCertificate(certC));
            certCol.Add(cf.ReadCertificate(certD));

//			CertPathBuilder pathBuilder = CertPathBuilder.GetInstance("PKIX");
            PkixCertPathBuilder   pathBuilder = new PkixCertPathBuilder();
            X509CertStoreSelector select      = new X509CertStoreSelector();

            select.Subject = ((X509Certificate)certCol[0]).SubjectDN;

            ISet trustanchors = new HashSet();

            trustanchors.Add(new TrustAnchor(cf.ReadCertificate(rootCertBin), null));

//			CertStore certStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certCol));
            IX509Store x509CertStore = X509StoreFactory.Create(
                "Certificate/Collection",
                new X509CollectionStoreParameters(certCol));

            PkixBuilderParameters parameters = new PkixBuilderParameters(trustanchors, select);

            parameters.AddStore(x509CertStore);

            try
            {
                PkixCertPathBuilderResult result = pathBuilder.Build(parameters);
                PkixCertPath path = result.CertPath;
                Fail("found cert path in circular set");
            }
            catch (PkixCertPathBuilderException)
            {
                // expected
            }
        }
Ejemplo n.º 32
0
        private void basicTest(AsymmetricKeyParameter privateKey, X509.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[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.º 33
0
        private PkixCertPathBuilderResult doBuilderTest(
            string trustAnchor,
            string[]        certs,
            string[]        crls,
            ISet initialPolicies,
            bool policyMappingInhibited,
            bool anyPolicyInhibited)
        {
            ISet trustedSet = new HashSet();

            trustedSet.Add(GetTrustAnchor(trustAnchor));

            IList           x509Certs = new ArrayList();
            IList           x509Crls  = new ArrayList();
            X509Certificate endCert   = LoadCert(certs[certs.Length - 1]);

            for (int i = 0; i != certs.Length - 1; i++)
            {
                x509Certs.Add(LoadCert(certs[i]));
            }

            x509Certs.Add(endCert);

            for (int i = 0; i != crls.Length; i++)
            {
                x509Crls.Add(LoadCrl(crls[i]));
            }

            IX509Store x509CertStore = X509StoreFactory.Create(
                "Certificate/Collection",
                new X509CollectionStoreParameters(x509Certs));
            IX509Store x509CrlStore = X509StoreFactory.Create(
                "CRL/Collection",
                new X509CollectionStoreParameters(x509Crls));

//			CertPathBuilder builder = CertPathBuilder.GetInstance("PKIX");
            PkixCertPathBuilder builder = new PkixCertPathBuilder();

            X509CertStoreSelector endSelector = new X509CertStoreSelector();

            endSelector.Certificate = endCert;

            PkixBuilderParameters builderParams = new PkixBuilderParameters(trustedSet, endSelector);

            if (initialPolicies != null)
            {
                builderParams.SetInitialPolicies(initialPolicies);
                builderParams.IsExplicitPolicyRequired = true;
            }
            if (policyMappingInhibited)
            {
                builderParams.IsPolicyMappingInhibited = policyMappingInhibited;
            }
            if (anyPolicyInhibited)
            {
                builderParams.IsAnyPolicyInhibited = anyPolicyInhibited;
            }

            builderParams.AddStore(x509CertStore);
            builderParams.AddStore(x509CrlStore);

            // Perform validation as of this date since test certs expired
            builderParams.Date = new DateTimeObject(DateTime.Parse("1/1/2011"));

            try
            {
                return((PkixCertPathBuilderResult)builder.Build(builderParams));
            }
            catch (PkixCertPathBuilderException e)
            {
                throw e.InnerException;
            }
        }
Ejemplo n.º 34
0
        public override void PerformTest()
        {
            X509CertificateParser certParser = new X509CertificateParser();
            X509CrlParser         crlParser  = new X509CrlParser();

            // initialise CertStore
            X509Certificate rootCert  = certParser.ReadCertificate(CertPathTest.rootCertBin);
            X509Certificate interCert = certParser.ReadCertificate(CertPathTest.interCertBin);
            X509Certificate finalCert = certParser.ReadCertificate(CertPathTest.finalCertBin);
            X509Crl         rootCrl   = crlParser.ReadCrl(CertPathTest.rootCrlBin);
            X509Crl         interCrl  = crlParser.ReadCrl(CertPathTest.interCrlBin);

            IList x509Certs = new ArrayList();

            x509Certs.Add(rootCert);
            x509Certs.Add(interCert);
            x509Certs.Add(finalCert);

            IList x509Crls = new ArrayList();

            x509Crls.Add(rootCrl);
            x509Crls.Add(interCrl);

//			CollectionCertStoreParameters ccsp = new CollectionCertStoreParameters(list);
//			CertStore store = CertStore.GetInstance("Collection", ccsp);
//			X509CollectionStoreParameters ccsp = new X509CollectionStoreParameters(list);
            IX509Store x509CertStore = X509StoreFactory.Create(
                "Certificate/Collection",
                new X509CollectionStoreParameters(x509Certs));
            IX509Store x509CrlStore = X509StoreFactory.Create(
                "CRL/Collection",
                new X509CollectionStoreParameters(x509Crls));

            // NB: Month is 1-based in .NET
            //DateTime validDate = new DateTime(2008,9,4,14,49,10).ToUniversalTime();
            DateTime validDate = new DateTime(2008, 9, 4, 5, 49, 10);

            //validating path
            IList certchain = new ArrayList();

            certchain.Add(finalCert);
            certchain.Add(interCert);

//			CertPath cp = CertificateFactory.GetInstance("X.509").GenerateCertPath(certchain);
            PkixCertPath cp    = new PkixCertPath(certchain);
            ISet         trust = new HashSet();

            trust.Add(new TrustAnchor(rootCert, null));

//			CertPathValidator cpv = CertPathValidator.GetInstance("PKIX");
            PkixCertPathValidator cpv   = new PkixCertPathValidator();
            PkixParameters        param = new PkixParameters(trust);

            param.AddStore(x509CertStore);
            param.AddStore(x509CrlStore);
            param.Date = new DateTimeObject(validDate);
            MyChecker checker = new MyChecker();

            param.AddCertPathChecker(checker);

            PkixCertPathValidatorResult result      = (PkixCertPathValidatorResult)cpv.Validate(cp, param);
            PkixPolicyNode         policyTree       = result.PolicyTree;
            AsymmetricKeyParameter subjectPublicKey = result.SubjectPublicKey;

            if (checker.GetCount() != 2)
            {
                Fail("checker not evaluated for each certificate");
            }

            if (!subjectPublicKey.Equals(finalCert.GetPublicKey()))
            {
                Fail("wrong public key returned");
            }

            IsTrue(result.TrustAnchor.TrustedCert.Equals(rootCert));

            // try a path with trust anchor included.
            certchain.Clear();
            certchain.Add(finalCert);
            certchain.Add(interCert);
            certchain.Add(rootCert);

            cp = new PkixCertPath(certchain);

            cpv   = new PkixCertPathValidator();
            param = new PkixParameters(trust);
            param.AddStore(x509CertStore);
            param.AddStore(x509CrlStore);
            param.Date = new DateTimeObject(validDate);
            checker    = new MyChecker();
            param.AddCertPathChecker(checker);

            result = (PkixCertPathValidatorResult)cpv.Validate(cp, param);

            IsTrue(result.TrustAnchor.TrustedCert.Equals(rootCert));

            //
            // invalid path containing a valid one test
            //
            try
            {
                // initialise CertStore
                rootCert  = certParser.ReadCertificate(AC_RAIZ_ICPBRASIL);
                interCert = certParser.ReadCertificate(AC_PR);
                finalCert = certParser.ReadCertificate(schefer);

                x509Certs = new ArrayList();
                x509Certs.Add(rootCert);
                x509Certs.Add(interCert);
                x509Certs.Add(finalCert);

//				ccsp = new CollectionCertStoreParameters(list);
//				store = CertStore.GetInstance("Collection", ccsp);
//				ccsp = new X509CollectionStoreParameters(list);
                x509CertStore = X509StoreFactory.Create(
                    "Certificate/Collection",
                    new X509CollectionStoreParameters(x509Certs));

                // NB: Month is 1-based in .NET
                //validDate = new DateTime(2004,3,21,2,21,10).ToUniversalTime();
                validDate = new DateTime(2004, 3, 20, 19, 21, 10);

                //validating path
                certchain = new ArrayList();
                certchain.Add(finalCert);
                certchain.Add(interCert);

//				cp = CertificateFactory.GetInstance("X.509").GenerateCertPath(certchain);
                cp    = new PkixCertPath(certchain);
                trust = new HashSet();
                trust.Add(new TrustAnchor(rootCert, null));

//				cpv = CertPathValidator.GetInstance("PKIX");
                cpv   = new PkixCertPathValidator();
                param = new PkixParameters(trust);
                param.AddStore(x509CertStore);
                param.IsRevocationEnabled = false;
                param.Date = new DateTimeObject(validDate);

                result           = (PkixCertPathValidatorResult)cpv.Validate(cp, param);
                policyTree       = result.PolicyTree;
                subjectPublicKey = result.SubjectPublicKey;

                Fail("Invalid path validated");
            }
            catch (Exception e)
            {
                if (e is PkixCertPathValidatorException &&
                    e.Message.StartsWith("Could not validate certificate signature."))
                {
                    return;
                }
                Fail("unexpected exception", e);
            }
        }
Ejemplo n.º 35
0
        /**
         * Replace the certificate and CRL information associated with this
         * CMSSignedData object with the new one passed in.
         * <p>
         * The output stream is returned unclosed.
         * </p>
         * @param original the signed data stream to be used as a base.
         * @param certsAndCrls the new certificates and CRLs to be used.
         * @param out the stream to Write the new signed data object to.
         * @return out.
         * @exception CmsException if there is an error processing the CertStore
         */
        public static Stream ReplaceCertificatesAndCrls(
            Stream original,
            IX509Store x509Certs,
            IX509Store x509Crls,
            IX509Store x509AttrCerts,
            Stream outStr)
        {
            if (x509AttrCerts != null)
            {
                throw new NotImplementedException("Currently can't replace attribute certificates");
            }

            Asn1StreamParser  inStr       = new Asn1StreamParser(original, CmsUtilities.MaximumMemory);
            ContentInfoParser contentInfo = new ContentInfoParser((Asn1SequenceParser)inStr.ReadObject());
            SignedDataParser  signedData  = SignedDataParser.GetInstance(contentInfo.GetContent(Asn1Tags.Sequence));

            BerSequenceGenerator sGen = new BerSequenceGenerator(outStr);

            sGen.AddObject(CmsObjectIdentifiers.SignedData);

            BerSequenceGenerator sigGen = new BerSequenceGenerator(sGen.GetRawOutputStream(), 0, true);

            // version number
            sigGen.AddObject(signedData.Version);

            // digests
            WriteToGenerator(sigGen, signedData.GetDigestAlgorithms().ToAsn1Object());

            // encap content info
            ContentInfoParser encapContentInfo = signedData.GetEncapContentInfo();

            BerSequenceGenerator eiGen = new BerSequenceGenerator(sigGen.GetRawOutputStream());

            eiGen.AddObject(encapContentInfo.ContentType);

            Asn1OctetStringParser octs = (Asn1OctetStringParser)encapContentInfo.GetContent(Asn1Tags.OctetString);

            if (octs != null)
            {
                BerOctetStringGenerator octGen = new BerOctetStringGenerator(eiGen.GetRawOutputStream(), 0, true);
                byte[] inBuffer  = new byte[4096];
                byte[] outBuffer = new byte[4096];
                Stream inOctets  = octs.GetOctetStream();
                Stream outOctets = octGen.GetOctetOutputStream(outBuffer);

                int len;
                while ((len = inOctets.Read(inBuffer, 0, inBuffer.Length)) > 0)
                {
                    outOctets.Write(inBuffer, 0, len);
                }

                outOctets.Close();
            }

            eiGen.Close();

            //
            // skip existing certs and CRLs
            //
            Asn1SetParser set = signedData.GetCertificates();

            if (set != null)
            {
                set.ToAsn1Object();
            }

            set = signedData.GetCrls();

            if (set != null)
            {
                set.ToAsn1Object();
            }

            //
            // replace the certs and crls in the SignedData object
            //
            Asn1Set certs;

            try
            {
                certs = CmsUtilities.CreateDerSetFromList(
                    CmsUtilities.GetCertificatesFromStore(x509Certs));
            }
            catch (X509StoreException e)
            {
                throw new CmsException("error getting certs from certStore", e);
            }

            if (certs.Count > 0)
            {
                WriteToGenerator(sigGen, new DerTaggedObject(false, 0, certs));
            }

            Asn1Set crls;

            try
            {
                crls = CmsUtilities.CreateDerSetFromList(
                    CmsUtilities.GetCrlsFromStore(x509Crls));
            }
            catch (X509StoreException e)
            {
                throw new CmsException("error getting crls from certStore", e);
            }

            if (crls.Count > 0)
            {
                WriteToGenerator(sigGen, new DerTaggedObject(false, 1, crls));
            }

            WriteToGenerator(sigGen, signedData.GetSignerInfos().ToAsn1Object());

            sigGen.Close();

            sGen.Close();

            return(outStr);
        }
Ejemplo n.º 36
0
		/**
		 * return a X509Store containing the public key certificates, if any, contained
		 * in this message.
		 *
		 * @param type type of store to create
		 * @return a store of public key certificates
		 * @exception NoSuchStoreException if the store type isn't available.
		 * @exception CmsException if a general exception prevents creation of the X509Store
		 */
		public IX509Store GetCertificates(
			string type)
		{
			if (certificateStore == null)
			{
				certificateStore = Helper.CreateCertificateStore(type, signedData.Certificates);
			}

			return certificateStore;
		}
Ejemplo n.º 37
0
		/**
		* Adds a Bouncy Castle {@link Store} to find CRLs, certificates, attribute
		* certificates or cross certificates.
		* <p>
		* This method should be used to add local stores, like collection based
		* X.509 stores, if available. Local stores should be considered first,
		* before trying to use additional (remote) locations, because they do not
		* need possible additional network traffic.
		* </p><p>
		* If <code>store</code> is <code>null</code> it is ignored.
		* </p>
		*
		* @param store The store to add.
		* @see #getStores
		*/
		public virtual void AddStore(
			IX509Store store)
		{
			if (store != null)
			{
				stores.Add(store);
			}
		}
Ejemplo n.º 38
0
		/**
		* Replace the certificate and CRL information associated with this
		* CmsSignedData object with the new one passed in.
		*
		* @param signedData the signed data object to be used as a base.
		* @param x509Certs the new certificates to be used.
		* @param x509Crls the new CRLs to be used.
		* @return a new signed data object.
		* @exception CmsException if there is an error processing the stores
		*/
		public static CmsSignedData ReplaceCertificatesAndCrls(
			CmsSignedData	signedData,
			IX509Store		x509Certs,
			IX509Store		x509Crls,
			IX509Store		x509AttrCerts)
		{
			if (x509AttrCerts != null)
				throw Platform.CreateNotImplementedException("Currently can't replace attribute certificates");

			//
			// copy
			//
			CmsSignedData cms = new CmsSignedData(signedData);

			//
			// replace the certs and crls in the SignedData object
			//
			Asn1Set certs = null;
			try
			{
				Asn1Set asn1Set = CmsUtilities.CreateBerSetFromList(
					CmsUtilities.GetCertificatesFromStore(x509Certs));

				if (asn1Set.Count != 0)
				{
					certs = asn1Set;
				}
			}
			catch (X509StoreException e)
			{
				throw new CmsException("error getting certificates from store", e);
			}

			Asn1Set crls = null;
			try
			{
				Asn1Set asn1Set = CmsUtilities.CreateBerSetFromList(
					CmsUtilities.GetCrlsFromStore(x509Crls));

				if (asn1Set.Count != 0)
				{
					crls = asn1Set;
				}
			}
			catch (X509StoreException e)
			{
				throw new CmsException("error getting CRLs from store", e);
			}

			//
			// replace the CMS structure.
			//
			SignedData old = signedData.signedData;
			cms.signedData = new SignedData(
				old.DigestAlgorithms,
				old.EncapContentInfo,
				certs,
				crls,
				old.SignerInfos);

			//
			// replace the contentInfo with the new one
			//
			cms.contentInfo = new ContentInfo(cms.contentInfo.ContentType, cms.signedData);

			return cms;
		}
		public void SetCertificates(
			IX509Store certificates)
		{
			this.x509Certs = certificates;
		}
 public void AddCertificates(IX509Store certStore)
 {
     CollectionUtilities.AddRange(_certs, CmsUtilities.GetCertificatesFromStore(certStore));
 }
Ejemplo n.º 41
0
        /**
         * Replace the certificate and CRL information associated with this
         * CmsSignedData object with the new one passed in.
         *
         * @param signedData the signed data object to be used as a base.
         * @param x509Certs the new certificates to be used.
         * @param x509Crls the new CRLs to be used.
         * @return a new signed data object.
         * @exception CmsException if there is an error processing the stores
         */
        public static CmsSignedData ReplaceCertificatesAndCrls(
            CmsSignedData signedData,
            IX509Store x509Certs,
            IX509Store x509Crls,
            IX509Store x509AttrCerts)
        {
            if (x509AttrCerts != null)
            {
                throw Platform.CreateNotImplementedException("Currently can't replace attribute certificates");
            }

            //
            // copy
            //
            CmsSignedData cms = new CmsSignedData(signedData);

            //
            // replace the certs and crls in the SignedData object
            //
            Asn1Set certs = null;

            try
            {
                Asn1Set asn1Set = CmsUtilities.CreateBerSetFromList(
                    CmsUtilities.GetCertificatesFromStore(x509Certs));

                if (asn1Set.Count != 0)
                {
                    certs = asn1Set;
                }
            }
            catch (X509StoreException e)
            {
                throw new CmsException("error getting certificates from store", e);
            }

            Asn1Set crls = null;

            try
            {
                Asn1Set asn1Set = CmsUtilities.CreateBerSetFromList(
                    CmsUtilities.GetCrlsFromStore(x509Crls));

                if (asn1Set.Count != 0)
                {
                    crls = asn1Set;
                }
            }
            catch (X509StoreException e)
            {
                throw new CmsException("error getting CRLs from store", e);
            }

            //
            // replace the CMS structure.
            //
            SignedData old = signedData.signedData;

            cms.signedData = new SignedData(
                old.DigestAlgorithms,
                old.EncapContentInfo,
                certs,
                crls,
                old.SignerInfos);

            //
            // replace the contentInfo with the new one
            //
            cms.contentInfo = new ContentInfo(cms.contentInfo.ContentType, cms.signedData);

            return(cms);
        }
Ejemplo n.º 42
0
        private void extensionTest(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs)
        {
            TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator(
                privateKey, cert, TspAlgorithms.Sha1, "1.2");

            tsTokenGen.SetCertificates(certs);

            TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator();

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

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

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

            ArrayList algorithms = new ArrayList();

            algorithms.Add(TspAlgorithms.Sha1);

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

            ArrayList policies = new ArrayList();

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

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

            ArrayList extensions = new ArrayList();

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


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

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

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

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

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

            TimeStampToken tsToken = tsResp.TimeStampToken;

            tsToken.Validate(cert);

            Asn1.Cms.AttributeTable table = tsToken.SignedAttributes;

            Assert.NotNull(table[PkcsObjectIdentifiers.IdAASigningCertificate], "no signingCertificate attribute found");
        }
Ejemplo n.º 43
0
		/**
		 * return a X509Store containing the attribute certificates, if any, contained
		 * in this message.
		 *
		 * @param type type of store to create
		 * @return a store of attribute certificates
		 * @exception NoSuchStoreException if the store type isn't available.
		 * @exception CmsException if a general exception prevents creation of the X509Store
		 */
		public IX509Store GetAttributeCertificates(
			string type)
		{
			if (attrCertStore == null)
			{
				attrCertStore = Helper.CreateAttributeStore(type, signedData.Certificates);
			}

			return attrCertStore;
		}
Ejemplo n.º 44
0
        /// <inheritdoc/>
        public Task <bool> ValidateRemoteCertificateAsync(X509Certificate target, ILogger?logger = null)
        {
            if (AcceptAllRemoteCertificates)
            {
                return(Task.FromResult(true));
            }

            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            var trustedCerts     = new Org.BouncyCastle.Utilities.Collections.HashSet();
            var trustedCertsInfo = new DirectoryInfo(Path.Combine(_pkiPath, "trusted"));

            if (!trustedCertsInfo.Exists)
            {
                trustedCertsInfo.Create();
            }

            foreach (var info in trustedCertsInfo.EnumerateFiles())
            {
                using (var crtStream = info.OpenRead())
                {
                    var crt = _certParser.ReadCertificate(crtStream);
                    if (crt != null)
                    {
                        trustedCerts.Add(crt);
                    }
                }
            }

            var intermediateCerts     = new Org.BouncyCastle.Utilities.Collections.HashSet();
            var intermediateCertsInfo = new DirectoryInfo(Path.Combine(_pkiPath, "issuer"));

            if (!intermediateCertsInfo.Exists)
            {
                intermediateCertsInfo.Create();
            }

            foreach (var info in intermediateCertsInfo.EnumerateFiles())
            {
                using (var crtStream = info.OpenRead())
                {
                    var crt = _certParser.ReadCertificate(crtStream);
                    if (crt != null)
                    {
                        intermediateCerts.Add(crt);
                    }
                }
            }

            if (IsSelfSigned(target))
            {
                // Create the selector that specifies the starting certificate
                var selector = new X509CertStoreSelector()
                {
                    Certificate = target
                };
                IX509Store trustedCertStore = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(trustedCerts));
                if (trustedCertStore.GetMatches(selector).Count > 0)
                {
                    return(Task.FromResult(true));
                }

                logger?.LogError($"Error validatingRemoteCertificate.");
                StoreInRejectedFolder(target);
                return(Task.FromResult(false));
            }

            try
            {
                var res = VerifyCertificate(target, trustedCerts, intermediateCerts);
            }
            catch (Exception ex)
            {
                logger?.LogError($"Error validatingRemoteCertificate. {ex.Message}");
                StoreInRejectedFolder(target);
                return(Task.FromResult(false));
            }

            return(Task.FromResult(true));
        }
Ejemplo n.º 45
0
		/**
		* return a X509Store containing CRLs, if any, contained
		* in this message.
		*
		* @param type type of store to create
		* @return a store of CRLs
		* @exception NoSuchStoreException if the store type isn't available.
		* @exception CmsException if a general exception prevents creation of the X509Store
		*/
		public IX509Store GetCrls(
			string type)
		{
			if (crlStore == null)
			{
				crlStore = Helper.CreateCrlStore(type, signedData.CRLs);
			}

			return crlStore;
		}
Ejemplo n.º 46
0
        /// <inheritdoc/>
        public async Task <(X509Certificate?Certificate, RsaKeyParameters?Key)> GetLocalCertificateAsync(ApplicationDescription applicationDescription, ILogger?logger = null)
        {
            if (applicationDescription == null)
            {
                throw new ArgumentNullException(nameof(applicationDescription));
            }

            string?applicationUri = applicationDescription.ApplicationUri;

            if (string.IsNullOrEmpty(applicationUri))
            {
                throw new ArgumentOutOfRangeException(nameof(applicationDescription), "Expecting ApplicationUri in the form of 'http://{hostname}/{appname}' -or- 'urn:{hostname}:{appname}'.");
            }

            string?subjectName = null;
            string?hostName    = null;
            string?appName     = null;

            UriBuilder appUri = new UriBuilder(applicationUri);

            if (appUri.Scheme == "http" && !string.IsNullOrEmpty(appUri.Host))
            {
                var path = appUri.Path.Trim('/');
                if (!string.IsNullOrEmpty(path))
                {
                    hostName    = appUri.Host;
                    appName     = path;
                    subjectName = $"CN={appName},DC={hostName}";
                }
            }

            if (appUri.Scheme == "urn")
            {
                var parts = appUri.Path.Split(new[] { ':' }, 2);
                if (parts.Length == 2)
                {
                    hostName    = parts[0];
                    appName     = parts[1];
                    subjectName = $"CN={appName},DC={hostName}";
                }
            }

            if (subjectName == null)
            {
                throw new ArgumentOutOfRangeException(nameof(applicationDescription), "Expecting ApplicationUri in the form of 'http://{hostname}/{appname}' -or- 'urn:{hostname}:{appname}'.");
            }

            var crt = default(X509Certificate);
            var key = default(RsaKeyParameters);

            // Build 'own/certs' certificate store.
            var ownCerts     = new Org.BouncyCastle.Utilities.Collections.HashSet();
            var ownCertsInfo = new DirectoryInfo(Path.Combine(_pkiPath, "own", "certs"));

            if (ownCertsInfo.Exists)
            {
                foreach (var info in ownCertsInfo.EnumerateFiles())
                {
                    using (var crtStream = info.OpenRead())
                    {
                        var c = _certParser.ReadCertificate(crtStream);
                        if (c != null)
                        {
                            ownCerts.Add(c);
                        }
                    }
                }
            }

            IX509Store ownCertStore = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(ownCerts));

            // Select the newest certificate that matches by subject name.
            var selector = new X509CertStoreSelector()
            {
                Subject = new X509Name(subjectName)
            };

            crt = ownCertStore.GetMatches(selector).OfType <X509Certificate>().OrderBy(c => c.NotBefore).LastOrDefault();
            if (crt != null)
            {
                // If certificate found, verify alt-name, and retrieve private key.
                var asn1OctetString = crt.GetExtensionValue(X509Extensions.SubjectAlternativeName);
                if (asn1OctetString != null)
                {
                    var          asn1Object = X509ExtensionUtilities.FromExtensionValue(asn1OctetString);
                    GeneralNames gns        = GeneralNames.GetInstance(asn1Object);
                    if (gns.GetNames().Any(n => n.TagNo == GeneralName.UniformResourceIdentifier && n.Name.ToString() == applicationUri))
                    {
                        var ki = new FileInfo(Path.Combine(_pkiPath, "own", "private", $"{crt.SerialNumber}.key"));
                        if (ki.Exists)
                        {
                            using (var keyStream = new StreamReader(ki.OpenRead()))
                            {
                                var keyReader = new PemReader(keyStream);
                                var keyPair   = keyReader.ReadObject() as AsymmetricCipherKeyPair;
                                if (keyPair != null)
                                {
                                    key = keyPair.Private as RsaKeyParameters;
                                }
                            }
                        }
                    }
                }
            }

            // If certificate and key are found, return to caller.
            if (crt != null && key != null)
            {
                logger?.LogTrace($"Found certificate with subject alt name '{applicationUri}'.");
                return(crt, key);
            }

            if (!CreateLocalCertificateIfNotExist)
            {
                return(null, null);
            }

            // Create new certificate
            var subjectDN = new X509Name(subjectName);

            // Create a keypair.
            var kp = await Task.Run <AsymmetricCipherKeyPair>(() =>
            {
                RsaKeyPairGenerator kg = new RsaKeyPairGenerator();
                kg.Init(new KeyGenerationParameters(_rng, 2048));
                return(kg.GenerateKeyPair());
            });

            key = kp.Private as RsaPrivateCrtKeyParameters;

            // Create a certificate.
            X509V3CertificateGenerator cg = new X509V3CertificateGenerator();
            var subjectSN = BigInteger.ProbablePrime(120, _rng);

            cg.SetSerialNumber(subjectSN);
            cg.SetSubjectDN(subjectDN);
            cg.SetIssuerDN(subjectDN);
            cg.SetNotBefore(DateTime.Now.Date.ToUniversalTime());
            cg.SetNotAfter(DateTime.Now.Date.ToUniversalTime().AddYears(25));
            cg.SetPublicKey(kp.Public);

            cg.AddExtension(
                X509Extensions.BasicConstraints.Id,
                true,
                new BasicConstraints(false));

            cg.AddExtension(
                X509Extensions.SubjectKeyIdentifier.Id,
                false,
                new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public)));

            cg.AddExtension(
                X509Extensions.AuthorityKeyIdentifier.Id,
                false,
                new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public), new GeneralNames(new GeneralName(subjectDN)), subjectSN));

            cg.AddExtension(
                X509Extensions.SubjectAlternativeName,
                false,
                new GeneralNames(new[] { new GeneralName(GeneralName.UniformResourceIdentifier, applicationUri), new GeneralName(GeneralName.DnsName, hostName) }));

            cg.AddExtension(
                X509Extensions.KeyUsage,
                true,
                new KeyUsage(KeyUsage.DataEncipherment | KeyUsage.DigitalSignature | KeyUsage.NonRepudiation | KeyUsage.KeyCertSign | KeyUsage.KeyEncipherment));

            cg.AddExtension(
                X509Extensions.ExtendedKeyUsage,
                true,
                new ExtendedKeyUsage(KeyPurposeID.IdKPClientAuth, KeyPurposeID.IdKPServerAuth));

            crt = cg.Generate(new Asn1SignatureFactory("SHA256WITHRSA", key, _rng));

            logger?.LogTrace($"Created certificate with subject alt name '{applicationUri}'.");

            var keyInfo = new FileInfo(Path.Combine(_pkiPath, "own", "private", $"{crt.SerialNumber}.key"));

            if (!keyInfo.Directory.Exists)
            {
                Directory.CreateDirectory(keyInfo.DirectoryName);
            }
            else if (keyInfo.Exists)
            {
                keyInfo.Delete();
            }

            using (var keystream = new StreamWriter(keyInfo.OpenWrite()))
            {
                var pemwriter = new PemWriter(keystream);
                pemwriter.WriteObject(key);
            }

            var crtInfo = new FileInfo(Path.Combine(_pkiPath, "own", "certs", $"{crt.SerialNumber}.crt"));

            if (!crtInfo.Directory.Exists)
            {
                Directory.CreateDirectory(crtInfo.DirectoryName);
            }
            else if (crtInfo.Exists)
            {
                crtInfo.Delete();
            }

            using (var crtstream = new StreamWriter(crtInfo.OpenWrite()))
            {
                var pemwriter = new PemWriter(crtstream);
                pemwriter.WriteObject(crt);
            }

            return(crt, key);
        }
Ejemplo n.º 47
0
 public void AddCertificates(
     IX509Store certStore)
 {
     _certs.AddRange(CmsUtilities.GetCertificatesFromStore(certStore));
 }
Ejemplo n.º 48
0
 public void AddCrls(
     IX509Store crlStore)
 {
     _crls.AddRange(CmsUtilities.GetCrlsFromStore(crlStore));
 }
 public void AddCrls(IX509Store crlStore)
 {
     CollectionUtilities.AddRange(_crls, CmsUtilities.GetCrlsFromStore(crlStore));
 }
Ejemplo n.º 50
0
 public void AddCertificates(
     IX509Store certStore)
 {
     CollectionUtilities.AddRange(_certs, CmsUtilities.GetCertificatesFromStore(certStore));
 }
Ejemplo n.º 51
0
        X509Certificate GetCertificate(IX509Store store, SignerID signer)
        {
            var matches = store.GetMatches (signer);

            foreach (X509Certificate certificate in matches) {
                return certificate;
            }

            return GetCertificate (signer);
        }
Ejemplo n.º 52
0
 public void AddCrls(
     IX509Store crlStore)
 {
     CollectionUtilities.AddRange(_crls, CmsUtilities.GetCrlsFromStore(crlStore));
 }
 public OriginatorInfoGenerator(IX509Store origCerts, IX509Store origCrls)
 {
     this.origCerts = CmsUtilities.GetCertificatesFromStore(origCerts);
     this.origCrls = origCrls == null ? null : CmsUtilities.GetCrlsFromStore(origCrls);
 }
 public OriginatorInfoGenerator(IX509Store origCerts)
     : this(origCerts, null)
 {
 }
Ejemplo n.º 55
0
		public void AddCrls(
			IX509Store crlStore)
		{
			_crls.AddRange(CmsUtilities.GetCrlsFromStore(crlStore));
		}
 public OriginatorInfoGenerator(IX509Store origCerts, IX509Store origCrls)
 {
     this.origCerts = CmsUtilities.GetCertificatesFromStore(origCerts);
     this.origCrls  = origCrls == null ? null : CmsUtilities.GetCrlsFromStore(origCrls);
 }
		/**
		 * return a X509Store containing the attribute certificates, if any, contained
		 * in this message.
		 *
		 * @param type type of store to create
		 * @return a store of attribute certificates
		 * @exception org.bouncycastle.x509.NoSuchStoreException if the store type isn't available.
		 * @exception CmsException if a general exception prevents creation of the X509Store
		 */
		public IX509Store GetAttributeCertificates(
			string type)
		{
			if (_attributeStore == null)
			{
				PopulateCertCrlSets();

				_attributeStore = Helper.CreateAttributeStore(type, _certSet);
			}

			return _attributeStore;
		}
Ejemplo n.º 58
0
        /**
         * Replace the certificate and CRL information associated with this
         * CMSSignedData object with the new one passed in.
         * <p>
         * The output stream is returned unclosed.
         * </p>
         * @param original the signed data stream to be used as a base.
         * @param certsAndCrls the new certificates and CRLs to be used.
         * @param out the stream to Write the new signed data object to.
         * @return out.
         * @exception CmsException if there is an error processing the CertStore
         */
        public static Stream ReplaceCertificatesAndCrls(
			Stream			original,
			IX509Store		x509Certs,
			IX509Store		x509Crls,
			IX509Store		x509AttrCerts,
			Stream			outStr)
        {
            if (x509AttrCerts != null)
                throw new NotImplementedException("Currently can't replace attribute certificates");

            Asn1StreamParser inStr = new Asn1StreamParser(original, CmsUtilities.MaximumMemory);
            ContentInfoParser contentInfo = new ContentInfoParser((Asn1SequenceParser)inStr.ReadObject());
            SignedDataParser signedData = SignedDataParser.GetInstance(contentInfo.GetContent(Asn1Tags.Sequence));

            BerSequenceGenerator sGen = new BerSequenceGenerator(outStr);

            sGen.AddObject(CmsObjectIdentifiers.SignedData);

            BerSequenceGenerator sigGen = new BerSequenceGenerator(sGen.GetRawOutputStream(), 0, true);

            // version number
            sigGen.AddObject(signedData.Version);

            // digests
            WriteToGenerator(sigGen, signedData.GetDigestAlgorithms().ToAsn1Object());

            // encap content info
            ContentInfoParser encapContentInfo = signedData.GetEncapContentInfo();

            BerSequenceGenerator eiGen = new BerSequenceGenerator(sigGen.GetRawOutputStream());

            eiGen.AddObject(encapContentInfo.ContentType);

            Asn1OctetStringParser octs = (Asn1OctetStringParser)encapContentInfo.GetContent(Asn1Tags.OctetString);

            if (octs != null)
            {
                BerOctetStringGenerator octGen = new BerOctetStringGenerator(eiGen.GetRawOutputStream(), 0, true);
                byte[] inBuffer = new byte[4096];
                byte[] outBuffer = new byte[4096];
                Stream inOctets = octs.GetOctetStream();
                Stream outOctets = octGen.GetOctetOutputStream(outBuffer);

                int len;
                while ((len = inOctets.Read(inBuffer, 0, inBuffer.Length)) > 0)
                {
                    outOctets.Write(inBuffer, 0, len);
                }

                outOctets.Close();
            }

            eiGen.Close();

            //
            // skip existing certs and CRLs
            //
            GetAsn1Set(signedData.GetCertificates());
            GetAsn1Set(signedData.GetCrls());

            //
            // replace the certs and crls in the SignedData object
            //
            Asn1Set certs;
            try
            {
                certs = CmsUtilities.CreateDerSetFromList(
                    CmsUtilities.GetCertificatesFromStore(x509Certs));
            }
            catch (X509StoreException e)
            {
                throw new CmsException("error getting certs from certStore", e);
            }

            if (certs.Count > 0)
            {
                WriteToGenerator(sigGen, new DerTaggedObject(false, 0, certs));
            }

            Asn1Set crls;
            try
            {
                crls = CmsUtilities.CreateDerSetFromList(
                    CmsUtilities.GetCrlsFromStore(x509Crls));
            }
            catch (X509StoreException e)
            {
                throw new CmsException("error getting crls from certStore", e);
            }

            if (crls.Count > 0)
            {
                WriteToGenerator(sigGen, new DerTaggedObject(false, 1, crls));
            }

            WriteToGenerator(sigGen, signedData.GetSignerInfos().ToAsn1Object());

            sigGen.Close();

            sGen.Close();

            return outStr;
        }
		/**
		 * Replace the certificate and CRL information associated with this
		 * CMSSignedData object with the new one passed in.
		 * <p>
		 * The output stream is returned unclosed.
		 * </p>
		 * @param original the signed data stream to be used as a base.
		 * @param certsAndCrls the new certificates and CRLs to be used.
		 * @param out the stream to Write the new signed data object to.
		 * @return out.
		 * @exception CmsException if there is an error processing the CertStore
		 */
		public static Stream ReplaceCertificatesAndCrls(
			Stream			original,
			IX509Store		x509Certs,
			IX509Store		x509Crls,
			IX509Store		x509AttrCerts,
			Stream			outStr)
		{
			// NB: SecureRandom would be ignored since using existing signatures only
			CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator();
			CmsSignedDataParser parser = new CmsSignedDataParser(original);

			gen.AddDigests(parser.DigestOids);

			CmsTypedStream signedContent = parser.GetSignedContent();
			bool encapsulate = (signedContent != null);
			Stream contentOut = gen.Open(outStr, parser.SignedContentType.Id, encapsulate);
			if (encapsulate)
			{
				Streams.PipeAll(signedContent.ContentStream, contentOut);
			}

//			gen.AddAttributeCertificates(parser.GetAttributeCertificates("Collection"));
//			gen.AddCertificates(parser.GetCertificates("Collection"));
//			gen.AddCrls(parser.GetCrls("Collection"));
			if (x509AttrCerts != null)
				gen.AddAttributeCertificates(x509AttrCerts);
			if (x509Certs != null)
				gen.AddCertificates(x509Certs);
			if (x509Crls != null)
				gen.AddCrls(x509Crls);

			gen.AddSigners(parser.GetSignerInfos());

			contentOut.Close();

			return outStr;
		}
        /// <summary>
        ///     Verify signed bytes and PKCS#7 signature.
        /// </summary>
        /// <param name="signedBytes">signed bytes</param>
        /// <param name="signatureBytes">signature bytes</param>
        /// <param name="data">other data</param>
        public void Verify(byte[] signedBytes, byte[] signatureBytes, CryptoSignatureVerificationData data = null)
        {
            if (signedBytes == null)
            {
                throw new ArgumentNullException(nameof(signedBytes));
            }

            if (signatureBytes == null)
            {
                throw new ArgumentNullException(nameof(signatureBytes));
            }

            if (_trustAnchors == null && data?.CertificateBytes == null)
            {
                throw new ArgumentException("No trust anchors given.");
            }

            CmsSignedData signedData;

            try
            {
                CmsProcessableByteArray cmsProcessableByteArray = new CmsProcessableByteArray(signedBytes);
                signedData = new CmsSignedData(cmsProcessableByteArray, signatureBytes);
            }
            catch (Exception e)
            {
                throw new PkiVerificationErrorException("Cannot create signature from " + nameof(signatureBytes), e);
            }

            SignerInformationStore signerInformationStore = signedData.GetSignerInfos();
            ICollection            signerCollection       = signerInformationStore.GetSigners();

            if (signerCollection.Count == 0)
            {
                throw new PkiVerificationFailedException("Signature does not contain any SignerInformation element.");
            }

            IX509Store x509Store = signedData.GetCertificates("collection");

            IEnumerator signerInfoCollectionEnumerator = signerCollection.GetEnumerator();

            while (signerInfoCollectionEnumerator.MoveNext())
            {
                SignerInformation signerInfo = (SignerInformation)signerInfoCollectionEnumerator.Current;

                if (signerInfo == null)
                {
                    throw new PkiVerificationErrorException("Signature does not contain any SignerInformation element.");
                }

                ICollection x509Collection = x509Store.GetMatches(signerInfo.SignerID);
                IEnumerator x509CertificateCollectionEnumerator = x509Collection.GetEnumerator();
                if (!x509CertificateCollectionEnumerator.MoveNext())
                {
                    throw new PkiVerificationErrorException("Signature does not contain any x509 certificates.");
                }

                X509Certificate certificate = (X509Certificate)x509CertificateCollectionEnumerator.Current;

                if (data != null)
                {
                    try
                    {
                        CertificateTimeVerifier.Verify(certificate, data.SignTime);
                    }
                    catch (PkiVerificationFailedCertNotValidException ex)
                    {
                        throw new PkiVerificationFailedCertNotValidException("PKCS#7 signature certificate is not valid.", ex);
                    }
                }

                if (_certificateRdnSelector != null)
                {
                    try
                    {
                        // Verify certificate with rdn selector
                        if (!_certificateRdnSelector.IsMatch(certificate))
                        {
                            throw new PkiVerificationFailedException("Certificate did not match with certificate subject rdn selector.");
                        }
                    }
                    catch (PkiVerificationFailedException)
                    {
                        throw;
                    }
                    catch (Exception e)
                    {
                        throw new PkiVerificationErrorException("Error when verifying PKCS#7 signature.", e);
                    }
                }

                try
                {
                    if (!signerInfo.Verify(certificate))
                    {
                        throw new PkiVerificationFailedException("Signer information does not match with certificate.");
                    }
                }
                catch (CmsException e)
                {
                    throw new PkiVerificationFailedException("Failed to verify PKCS#7 signature.", e);
                }
                catch (Exception e)
                {
                    throw new PkiVerificationErrorException("Error when verifying PKCS#7 signature.", e);
                }

                ISet trustAnchors;

                if (data?.CertificateBytes != null)
                {
                    try
                    {
                        trustAnchors = new HashSet
                        {
                            new TrustAnchor(DotNetUtilities.FromX509Certificate(new X509Certificate2(data.CertificateBytes)), null)
                        };
                    }
                    catch (Exception e)
                    {
                        throw new PkiVerificationErrorException("Cannot create trust anchor certificate from " + nameof(data.CertificateBytes), e);
                    }
                }
                else
                {
                    trustAnchors = _trustAnchors;
                }

                try
                {
                    ValidateCertPath(certificate, x509Store, trustAnchors);
                }
                catch (PkiVerificationFailedException)
                {
                    throw;
                }

                catch (Exception e)
                {
                    throw new PkiVerificationErrorException("Error when verifying PKCS#7 signature.", e);
                }
            }
        }