当前位置: 首页>>代码示例>>C#>>正文


C# X509Chain.Build方法代码示例

本文整理汇总了C#中X509Chain.Build方法的典型用法代码示例。如果您正苦于以下问题:C# X509Chain.Build方法的具体用法?C# X509Chain.Build怎么用?C# X509Chain.Build使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在X509Chain的用法示例。


在下文中一共展示了X509Chain.Build方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: VerifyCrlCache

        public static void VerifyCrlCache()
        {
            string crlDirectory = PersistedFiles.GetUserFeatureDirectory("cryptography", "crls");
            string crlFile = Path.Combine(crlDirectory,MicrosoftDotComRootCrlFilename);

            Directory.CreateDirectory(crlDirectory);
            File.Delete(crlFile);

            using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes))
            using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
            using (var unrelated = new X509Certificate2(TestData.DssCer))
            {
                X509Chain chain = new X509Chain();

                chain.ChainPolicy.ExtraStore.Add(unrelated);
                chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot);
                
                // The very start of the CRL period.
                chain.ChainPolicy.VerificationTime = new DateTime(2015, 6, 17, 0, 0, 0, DateTimeKind.Utc);
                chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
                chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EndCertificateOnly;
                chain.ChainPolicy.VerificationFlags |= X509VerificationFlags.AllowUnknownCertificateAuthority;

                bool valid = chain.Build(microsoftDotComIssuer);
                Assert.True(valid, "Precondition: Chain builds with no revocation checks");

                int initialErrorCount = chain.ChainStatus.Length;
                Assert.InRange(initialErrorCount, 0, 1);

                if (initialErrorCount > 0)
                {
                    Assert.Equal(X509ChainStatusFlags.UntrustedRoot, chain.ChainStatus[0].Status);
                }

                chain.ChainPolicy.RevocationMode = X509RevocationMode.Offline;

                valid = chain.Build(microsoftDotComIssuer);
                Assert.False(valid, "Chain should not build validly");

                Assert.Equal(initialErrorCount + 1, chain.ChainStatus.Length);
                Assert.Equal(X509ChainStatusFlags.RevocationStatusUnknown, chain.ChainStatus[0].Status);

                File.WriteAllText(crlFile, MicrosoftDotComRootCrlPem, Encoding.ASCII);

                valid = chain.Build(microsoftDotComIssuer);
                Assert.True(valid, "Chain should build validly now");
                Assert.Equal(initialErrorCount, chain.ChainStatus.Length);

                // Rewind one second, the CRL is not "not yet valid"
                chain.ChainPolicy.VerificationTime = chain.ChainPolicy.VerificationTime.Subtract(TimeSpan.FromSeconds(1));

                valid = chain.Build(microsoftDotComIssuer);
                Assert.False(valid, "Chain should not build validly, CRL is not yet valid");

                Assert.Equal(initialErrorCount + 1, chain.ChainStatus.Length);
                Assert.Equal(X509ChainStatusFlags.RevocationStatusUnknown, chain.ChainStatus[0].Status);
            }
        }
开发者ID:er0dr1guez,项目名称:corefx,代码行数:58,代码来源:X509FilesystemTests.Unix.cs

示例2: BuildChain

        public static void BuildChain()
        {
            using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
            using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes))
            using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
            using (var unrelated = new X509Certificate2(TestData.DssCer))
            {
                X509Chain chain = new X509Chain();

                chain.ChainPolicy.ExtraStore.Add(unrelated);
                chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot);
                chain.ChainPolicy.ExtraStore.Add(microsoftDotComIssuer);
                chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;

                // Halfway between microsoftDotCom's NotBefore and NotAfter
                // This isn't a boundary condition test.
                chain.ChainPolicy.VerificationTime = new DateTime(2015, 10, 15, 12, 01, 01, DateTimeKind.Local);
                chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;

                bool valid = chain.Build(microsoftDotCom);
                Assert.True(valid, "Chain built validly");

                // The chain should have 3 members
                Assert.Equal(3, chain.ChainElements.Count);

                // These are the three specific members.
                Assert.Equal(microsoftDotCom, chain.ChainElements[0].Certificate);
                Assert.Equal(microsoftDotComIssuer, chain.ChainElements[1].Certificate);
                Assert.Equal(microsoftDotComRoot, chain.ChainElements[2].Certificate);
            }
        }
开发者ID:er0dr1guez,项目名称:corefx,代码行数:31,代码来源:ChainTests.cs

示例3: BuildChainExtraStoreUntrustedRoot

        public static void BuildChainExtraStoreUntrustedRoot()
        {
            using (var testCert = new X509Certificate2(Path.Combine("TestData", "test.pfx"), TestData.ChainPfxPassword))
            {
                X509Certificate2Collection collection = new X509Certificate2Collection();
                collection.Import(Path.Combine("TestData", "test.pfx"), TestData.ChainPfxPassword, X509KeyStorageFlags.DefaultKeySet);

                X509Chain chain = new X509Chain();
                chain.ChainPolicy.ExtraStore.AddRange(collection);
                chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
                chain.ChainPolicy.VerificationTime = new DateTime(2015, 9, 22, 12, 25, 0);

                bool valid = chain.Build(testCert);

                Assert.False(valid);
                Assert.Contains(chain.ChainStatus, s => s.Status == X509ChainStatusFlags.UntrustedRoot);
            }
        }
开发者ID:er0dr1guez,项目名称:corefx,代码行数:18,代码来源:ChainTests.cs

示例4: Test

	public static void Test(X509IncludeOption include)
		{
		cert = EndCert ;
		X509Chain chain = new X509Chain() ; 
		chain.Build( cert ) ; 

		X509ChainElementCollection lmnts = chain.ChainElements ; 
		
		KeyInfoX509Data data = new KeyInfoX509Data( cert, include )  ; 	
		ArrayList al = data.Certificates ; 
		if( al == null ) return ; 
		for( int i = 0 ; i < al.Count ; i++ ) 
			{
			rv = lmnts[i].Certificate.ToString(true) == ((X509Certificate) al[i]).ToString(true) ;
			if( !rv ) 		
				Console.WriteLine( "i  = " + i.ToString() + " and include=" + include.ToString() ) ; 
			}
		Console.WriteLine( "*************************************************************" ) ; 
		}
开发者ID:aura1213,项目名称:netmf-interpreter,代码行数:19,代码来源:x509datatest.cs

示例5: MyRemoteCertificateValidationCallback

 public static bool MyRemoteCertificateValidationCallback(System.Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
 {
     bool isOk = true;
     // If there are errors in the certificate chain, look at each error to determine the cause.
     if (sslPolicyErrors != SslPolicyErrors.None) {
         for (int i=0; i<chain.ChainStatus.Length; i++) {
             if (chain.ChainStatus [i].Status != X509ChainStatusFlags.RevocationStatusUnknown) {
                 chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
                 chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
                 chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan (0, 1, 0);
                 chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags;
                 bool chainIsValid = chain.Build ((X509Certificate2)certificate);
                 if (!chainIsValid) {
                     isOk = false;
                 }
             }
         }
     }
     return isOk;
 }
开发者ID:sandybisaria,项目名称:Jarvis,代码行数:20,代码来源:BingAPIManager.cs

示例6: BuildChain_WithCertificatePolicy_NoMatch

        public static void BuildChain_WithCertificatePolicy_NoMatch()
        {
            using (var cert = new X509Certificate2(TestData.CertWithPolicies))
            using (X509Chain chain = new X509Chain())
            {
                chain.ChainPolicy.CertificatePolicy.Add(new Oid("2.999"));
                chain.ChainPolicy.VerificationFlags =
                    X509VerificationFlags.AllowUnknownCertificateAuthority;

                chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
                chain.ChainPolicy.VerificationTime = cert.NotBefore.AddHours(2);

                bool valid = chain.Build(cert);
                Assert.False(valid, "Chain built validly");

                Assert.InRange(chain.ChainElements.Count, 1, int.MaxValue);

                Assert.NotSame(cert, chain.ChainElements[0].Certificate);
                Assert.Equal(cert, chain.ChainElements[0].Certificate);

                X509ChainStatus[] chainElementStatus = chain.ChainElements[0].ChainElementStatus;
                Assert.InRange(chainElementStatus.Length, 1, int.MaxValue);
                Assert.Contains(chainElementStatus, x => x.Status == X509ChainStatusFlags.NotValidForUsage);
            }
        }
开发者ID:benpye,项目名称:corefx,代码行数:25,代码来源:ChainTests.cs

示例7: VerifyExpiration_LocalTime

        public static void VerifyExpiration_LocalTime(DateTime verificationTime, bool shouldBeValid, DateTimeKind kind)
        {
            using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
            using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes))
            using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
            {
                X509Chain chain = new X509Chain();

                chain.ChainPolicy.ExtraStore.Add(microsoftDotComIssuer);
                chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot);

                // Ignore anything except NotTimeValid
                chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags & ~X509VerificationFlags.IgnoreNotTimeValid;
                chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
                chain.ChainPolicy.VerificationTime = verificationTime;

                bool builtSuccessfully = chain.Build(microsoftDotCom);

                Assert.Equal(shouldBeValid, builtSuccessfully);

                // If we failed to build the chain, ensure that NotTimeValid is one of the reasons.
                if (!shouldBeValid)
                {
                    Assert.Contains(chain.ChainStatus, s => s.Status == X509ChainStatusFlags.NotTimeValid);
                }
            }
        }
开发者ID:er0dr1guez,项目名称:corefx,代码行数:27,代码来源:ChainTests.cs

示例8: BuildChain_WithApplicationPolicy_Match

        public static void BuildChain_WithApplicationPolicy_Match()
        {
            using (var msCer = new X509Certificate2(TestData.MsCertificate))
            using (X509Chain chain = new X509Chain())
            {
                // Code Signing
                chain.ChainPolicy.ApplicationPolicy.Add(new Oid("1.3.6.1.5.5.7.3.3"));
                chain.ChainPolicy.VerificationTime = msCer.NotBefore.AddHours(2);
                chain.ChainPolicy.VerificationFlags =
                    X509VerificationFlags.AllowUnknownCertificateAuthority;

                chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;

                bool valid = chain.Build(msCer);
                Assert.True(valid, "Chain built validly");
            }
        }
开发者ID:benpye,项目名称:corefx,代码行数:17,代码来源:ChainTests.cs

示例9: BuildChain_WithCertificatePolicy_Match

        public static void BuildChain_WithCertificatePolicy_Match()
        {
            using (var cert = new X509Certificate2(TestData.CertWithPolicies))
            using (X509Chain chain = new X509Chain())
            {
                // Code Signing
                chain.ChainPolicy.CertificatePolicy.Add(new Oid("2.18.19"));
                chain.ChainPolicy.VerificationFlags =
                    X509VerificationFlags.AllowUnknownCertificateAuthority;
                chain.ChainPolicy.VerificationTime = cert.NotBefore.AddHours(2);

                chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;

                bool valid = chain.Build(cert);
                Assert.True(valid, "Chain built validly");
            }
        }
开发者ID:benpye,项目名称:corefx,代码行数:17,代码来源:ChainTests.cs

示例10: Verify

		public bool Verify ()
		{
			X509Chain chain = new X509Chain ();
			if (!chain.Build (this))
				return false;
			// TODO - check chain and other stuff ???
			return true;
		}
开发者ID:jjenki11,项目名称:blaze-chem-rendering,代码行数:8,代码来源:X509CertificateEx.cs

示例11: LogVerifyErrors

 private void LogVerifyErrors(X509Certificate2 cert, string testName)
 {
     // Emulate cert.Verify() implementation in order to capture and log errors.
     try
     {
         using (var chain = new X509Chain())
         {
             if (!chain.Build(cert))
             {
                 foreach (X509ChainStatus chainStatus in chain.ChainStatus)
                 {
                     _log.WriteLine(string.Format($"X509Certificate2.Verify error: {testName}, {chainStatus.Status}, {chainStatus.StatusInformation}"));
                 }
             }
             else
             {
                 _log.WriteLine(string.Format($"X509Certificate2.Verify expected error; received none: {testName}"));
             }
         }
     }
     catch (Exception e)
     {
         _log.WriteLine($"X509Certificate2.Verify exception: {testName}, {e}");
     }
 }
开发者ID:chcosta,项目名称:corefx,代码行数:25,代码来源:CertTests.cs

示例12: X509ChainElementCollection_IndexerVsEnumerator

        public static void X509ChainElementCollection_IndexerVsEnumerator()
        {
            using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
            using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes))
            using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
            using (X509Chain chain = new X509Chain())
            {
                chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot);
                chain.ChainPolicy.ExtraStore.Add(microsoftDotComIssuer);
                chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;

                // Halfway between microsoftDotCom's NotBefore and NotAfter
                // This isn't a boundary condition test.
                chain.ChainPolicy.VerificationTime = new DateTime(2015, 10, 15, 12, 01, 01, DateTimeKind.Local);
                chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;

                bool valid = chain.Build(microsoftDotCom);
                Assert.True(valid, "Precondition: Chain built validly");

                int position = 0;

                foreach (X509ChainElement chainElement in chain.ChainElements)
                {
                    X509ChainElement indexerElement = chain.ChainElements[position];

                    Assert.NotNull(chainElement);
                    Assert.NotNull(indexerElement);

                    Assert.Same(indexerElement, chainElement);
                    position++;
                }
            }
        }
开发者ID:SGuyGe,项目名称:corefx,代码行数:33,代码来源:CollectionTests.cs

示例13: VerifyClientCertificate

        private static int VerifyClientCertificate(int preverify_ok, IntPtr x509_ctx_ptr)
        {
            using (SafeX509StoreCtxHandle storeHandle = new SafeX509StoreCtxHandle(x509_ctx_ptr, false))
            {
                using (var chain = new X509Chain())
                {
                    chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
                    chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;

                    using (SafeX509StackHandle chainStack = Crypto.X509StoreCtxGetChain(storeHandle))
                    {
                        if (chainStack.IsInvalid)
                        {
                            Debug.Fail("Invalid chain stack handle");
                            return 0;
                        }

                        IntPtr certPtr = Crypto.GetX509StackField(chainStack, 0);
                        if (IntPtr.Zero == certPtr)
                        {
                            return 0;
                        }

                        using (X509Certificate2 cert = new X509Certificate2(certPtr))
                        {
                            return chain.Build(cert) ? 1 : 0;
                        }
                    }
                }
            }
        }
开发者ID:ardacetinkaya,项目名称:corefx,代码行数:31,代码来源:Interop.OpenSsl.cs

示例14: validateCertificates

		private void validateCertificates(X509CertificateCollection certificates)
		{
			ClientContext		context			= (ClientContext)this.Context;
			AlertDescription	description		= AlertDescription.BadCertificate;

#if NET_2_0
			if (context.SslStream.HaveRemoteValidation2Callback) {
				if (context.SslStream.RaiseServerCertificateValidation2 (certificates))
					return;
				// Give a chance to the 1.x ICertificatePolicy callback
			}
#endif
			// the leaf is the web server certificate
			X509Certificate leaf = certificates [0];
			X509Cert.X509Certificate cert = new X509Cert.X509Certificate (leaf.RawData);

			ArrayList errors = new ArrayList();

			// SSL specific check - not all certificates can be 
			// used to server-side SSL some rules applies after 
			// all ;-)
			if (!checkCertificateUsage (leaf)) 
			{
				// WinError.h CERT_E_PURPOSE 0x800B0106
				errors.Add ((int)-2146762490);
			}

			// SSL specific check - does the certificate match 
			// the host ?
			if (!checkServerIdentity (leaf))
			{
				// WinError.h CERT_E_CN_NO_MATCH 0x800B010F
				errors.Add ((int)-2146762481);
			}

			// Note: building and verifying a chain can take much time
			// so we do it last (letting simple things fails first)

			// Note: In TLS the certificates MUST be in order (and
			// optionally include the root certificate) so we're not
			// building the chain using LoadCertificate (it's faster)

			// Note: IIS doesn't seem to send the whole certificate chain
			// but only the server certificate :-( it's assuming that you
			// already have this chain installed on your computer. duh!
			// http://groups.google.ca/groups?q=IIS+server+certificate+chain&hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=85058s%24avd%241%40nnrp1.deja.com&rnum=3

			// we must remove the leaf certificate from the chain
			X509CertificateCollection chain = new X509CertificateCollection (certificates);
			chain.Remove (leaf);
			X509Chain verify = new X509Chain (chain);

			bool result = false;

			try
			{
				result = verify.Build (leaf);
			}
			catch (Exception)
			{
				result = false;
			}

			// Attempt to use OSX certificates
			//
			// Ideally we should return the SecTrustResult
#if !MONOTOUCH
			if (System.IO.File.Exists (OSX509Certificates.SecurityLibrary)){
#endif
				OSX509Certificates.SecTrustResult trustResult =  OSX509Certificates.TrustEvaluateSsl (certificates);

				// We could use the other values of trustResult to pass this extra information to the .NET 2 callback
				// for values like SecTrustResult.Confirm
				result = (trustResult == OSX509Certificates.SecTrustResult.Proceed ||
					  trustResult == OSX509Certificates.SecTrustResult.Unspecified);
#if !MONOTOUCH
			}
#endif
			
			if (!result) 
			{
				switch (verify.Status) 
				{
					case X509ChainStatusFlags.InvalidBasicConstraints:
						// WinError.h TRUST_E_BASIC_CONSTRAINTS 0x80096019
						errors.Add ((int)-2146869223);
						break;
					
					case X509ChainStatusFlags.NotSignatureValid:
						// WinError.h TRUST_E_BAD_DIGEST 0x80096010
						errors.Add ((int)-2146869232);
						break;
					
					case X509ChainStatusFlags.NotTimeNested:
						// WinError.h CERT_E_VALIDITYPERIODNESTING 0x800B0102
						errors.Add ((int)-2146762494);
						break;
					
					case X509ChainStatusFlags.NotTimeValid:
						// WinError.h CERT_E_EXPIRED 0x800B0101
//.........这里部分代码省略.........
开发者ID:tgiphil,项目名称:Mono-Class-Libraries,代码行数:101,代码来源:TlsServerCertificate.cs

示例15: ValidateServerCertificate

	private static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
	{
		if (sslPolicyErrors == SslPolicyErrors.None)
        	return true;
		
		if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != 0)
		{
			if (chain != null && chain.ChainStatus != null)
	        {
				X509Certificate2 cert2 = new X509Certificate2(certificate);
				chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
				//chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
				//chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(1000);
				//chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags;
				//chain.ChainPolicy.VerificationTime = DateTime.Now;
				chain.Build(cert2);
				
				foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus status in chain.ChainStatus)
				{
				    if ((certificate.Subject == certificate.Issuer) &&
				       (status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot)) 
				    {
				      // Self-signed certificates with an untrusted root are valid. 
				      continue;
				    }
				    else
				    {
				      if (status.Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError)
				      {
				        // If there are any other errors in the certificate chain, the certificate is invalid,
				     	// so the method returns false.
				        return false;
				      }
				    }
				}
	        }
			
        	return true;
		}
		
	    // Do not allow this client to communicate with unauthenticated servers. 
	    return false;
	}	
开发者ID:Vlanta,项目名称:c-sharp,代码行数:43,代码来源:PubnubExample.cs


注:本文中的X509Chain.Build方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。