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


C# SslStream.AuthenticateAsClientAsync方法代码示例

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


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

示例1: Main

        public static void Main(string[] args)
        {
            Console.WriteLine("Starting...");
            X509Certificate2 serverCertificate = new X509Certificate2("certificate.pfx"); // Any valid certificate with private key will work fine.
            TcpListener listener = new TcpListener(IPAddress.Any, 4567);
            TcpClient client = new TcpClient();
            listener.Start();

            Task clientConnectTask = client.ConnectAsync(IPAddress.Loopback, 4567);
            Task<TcpClient> listenerAcceptTask = listener.AcceptTcpClientAsync();
            Task.WaitAll(clientConnectTask, listenerAcceptTask);

            TcpClient server = listenerAcceptTask.Result;
            SslStream clientStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null, EncryptionPolicy.RequireEncryption);
            SslStream serverStream = new SslStream(server.GetStream(), false, null, null, EncryptionPolicy.RequireEncryption);

            Task clientAuthenticationTask = clientStream.AuthenticateAsClientAsync(serverCertificate.GetNameInfo(X509NameType.SimpleName, false), null, SslProtocols.Tls12, false);
            Task serverAuthenticationTask = serverStream.AuthenticateAsServerAsync(serverCertificate, false, SslProtocols.Tls12, false);
            Task.WaitAll(clientAuthenticationTask, serverAuthenticationTask);
            
            byte[] readBuffer = new byte[256];
            Task<int> readTask = clientStream.ReadAsync(readBuffer, 0, readBuffer.Length); // Create a pending ReadAsync, which will wait for data that will never come (for testing purposes).
            byte[] writeBuffer = new byte[256];
            Task writeTask = clientStream.WriteAsync(writeBuffer, 0, writeBuffer.Length); // The main thread actually blocks here (not asychronously waits) on .NET Core making this call.
            bool result = Task.WaitAll(new Task[1] { writeTask }, 5000); // This code won't even be reached on .NET Core. Works fine on .NET Framework.

            if (result)
            {
                Console.WriteLine("WriteAsync completed successfully while ReadAsync was pending... nothing locked up.");
            }
            else
            {
                Console.WriteLine("WriteAsync failed to complete after 5 seconds.");
            }
        }
开发者ID:xanather,项目名称:SslStreamTest,代码行数:35,代码来源:Program.cs

示例2: DesktopNetworkStream

        /// <summary>
        /// Initializes a client instance of <see cref="DesktopNetworkStream"/>.
        /// </summary>
        /// <param name="host">Network host.</param>
        /// <param name="port">Network port.</param>
        /// <param name="useTls">Use TLS layer?</param>
        /// <param name="noDelay">No delay?</param>
        /// <param name="ignoreSslPolicyErrors">Ignore SSL policy errors?</param>
        internal DesktopNetworkStream(string host, int port, bool useTls, bool noDelay, bool ignoreSslPolicyErrors)
        {
            this.Host = host;
            this.Port = port;
#if NETSTANDARD
            this.tcpClient = new TcpClient { NoDelay = noDelay };
            this.tcpClient.ConnectAsync(host, port).Wait();
#else
            this.tcpClient = new TcpClient(host, port) { NoDelay = noDelay };
#endif

            Stream stream = this.tcpClient.GetStream();
            if (useTls)
            {
                var ssl = new SslStream(
                    stream,
                    false,
                    (sender, certificate, chain, errors) => errors == SslPolicyErrors.None || ignoreSslPolicyErrors);
#if NETSTANDARD
                ssl.AuthenticateAsClientAsync(host).Wait();
#else
                ssl.AuthenticateAsClient(host);
#endif
                stream = ssl;
            }

            this.networkStream = stream;
        }
开发者ID:aerik,项目名称:fo-dicom,代码行数:36,代码来源:DesktopNetworkStream.cs

示例3: Discover

        public ServiceEndPoint Discover(ServiceEndPoint serviceEndpoint)
        {
            try
            {
                using (var client = CreateConnectedTcpClient(serviceEndpoint))
                {
                    using (var stream = client.GetStream())
                    {
                        using (var ssl = new SslStream(stream, false, ValidateCertificate))
                        {
                            ssl.AuthenticateAsClientAsync(serviceEndpoint.BaseUri.Host, new X509Certificate2Collection(), SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, false)
                                .GetAwaiter()
                                .GetResult();
                            ssl.Write(HelloLine, 0, HelloLine.Length);
                            ssl.Flush();

                            if (ssl.RemoteCertificate == null)
                                throw new Exception("The server did not provide an SSL certificate");

                            return new ServiceEndPoint(serviceEndpoint.BaseUri, new X509Certificate2(ssl.RemoteCertificate.Export(X509ContentType.Cert)).Thumbprint);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new HalibutClientException(ex.Message, ex);
            }
        }
开发者ID:OctopusDeploy,项目名称:Halibut,代码行数:29,代码来源:DiscoveryClient.cs

示例4: PostEmailAsync

 public override Task PostEmailAsync(string name, string[] to, string[] cc, string[] bcc, string subject, string message, params Attachment[] Attachments)
 {
     if (!ssl)
         return Task.Factory.StartNew(async () =>
         {
             using (var client = new TcpClient())
             {
                 await client.ConnectAsync(server, port);
                 using (var stream = client.GetStream())
                 using (var reader = new StreamReader(stream))
                 using (var writer = new StreamWriter(stream) { AutoFlush = true, NewLine = "\r\n" })
                 {
                     TcpWrite(writer, reader, name, to, cc, bcc, subject, message, Attachments);
                 }
             }
         });
     else
         return Task.Factory.StartNew(async () =>
         {
             using (var client = new TcpClient())
             {
                 await client.ConnectAsync(server, port);
                 using (var stream = new SslStream(client.GetStream(), false))
                 {
                     await stream.AuthenticateAsClientAsync(server);
                     using (var reader = new StreamReader(stream))
                     using (var writer = new StreamWriter(stream) { AutoFlush = true, NewLine = "\r\n" })
                     {
                         TcpWrite(writer, reader, name, to, cc, bcc, subject, message, Attachments);
                     }
                 }
             }
         });
 }
开发者ID:yonglehou,项目名称:dotNETCore-Extensions,代码行数:34,代码来源:SmtpEmailSender.cs

示例5: ConnectAsync

 public async Task<Stream> ConnectAsync(string host, int port, X509Certificate clientCert, CancellationToken cancel)
 {
     Stream lowerStream = null;
     SslStream sslStream = null;
     X509CertificateCollection certCollection = null;;
     if (clientCert != null)
     {
         certCollection = new X509CertificateCollection(new[] { clientCert });
     }
     try
     {
         lowerStream = await _connectionResolver.ConnectAsync(host, port, cancel);
         sslStream = new SslStream(lowerStream);
         await sslStream.AuthenticateAsClientAsync(host, certCollection, _protocols, checkCertificateRevocation: true);
         return sslStream;
     }
     catch (Exception)
     {
         if (sslStream != null)
         {
             sslStream.Dispose();
         }
         if (lowerStream != null)
         {
             lowerStream.Dispose();
         }
         throw;
     }
 }
开发者ID:Tratcher,项目名称:HTTP-SPEED-PLUS-MOBILITY,代码行数:29,代码来源:SslConnectionResolver.cs

示例6: InitRemoteStream

 async protected override Task InitRemoteStream()
 {
     await base.InitRemoteStream();
     var secureRemoteStream = new SslStream(RemoteStream, true, RemoteCertificateValidator);
     var targetHost = WrapperRequest.Prologue.Headers.First(x => x.Key == "Host").Value;
     await secureRemoteStream.AuthenticateAsClientAsync(targetHost);
     SecureRemoteStream = secureRemoteStream;
 }
开发者ID:swsmile,项目名称:SharpProxy,代码行数:8,代码来源:ProxySslRequest.cs

示例7: Connect

        public async Task Connect ()
        {
            if (IsConnected ())
                return;

            tcp = new TcpClient ();

            // Disable Nagle for HTTP/2
            tcp.NoDelay = true;

            await tcp.ConnectAsync (Host, (int)Port);

            if (UseTls) {
                sslStream = new SslStream (tcp.GetStream (), false, 
                    (sender, certificate, chain, sslPolicyErrors) => true);
                
                await sslStream.AuthenticateAsClientAsync (
                    Host, 
                    Certificates ?? new X509CertificateCollection (), 
                    System.Security.Authentication.SslProtocols.Tls12, 
                    false);

                clientStream = sslStream;
            } else {
                clientStream = tcp.GetStream ();
            }

            // Send out preface data
            var prefaceData = System.Text.Encoding.ASCII.GetBytes (ConnectionPreface);
            await clientStream.WriteAsync (prefaceData, 0, prefaceData.Length);
            await clientStream.FlushAsync ();
            
            // Start reading the stream on another thread
            var readTask = Task.Factory.StartNew (() => {
                try { read (); }
                catch (Exception ex) {
                    Console.WriteLine ("Read error: " + ex);
                    Disconnect ();
                }
            }, TaskCreationOptions.LongRunning);

            readTask.ContinueWith (t => {
                // TODO: Handle the error
                Console.WriteLine ("Error: " + t.Exception);
                Disconnect ();
            }, TaskContinuationOptions.OnlyOnFaulted);

            // Send an un-ACK'd settings frame
            await SendFrame(new SettingsFrame ());

            // We need to wait for settings server preface to come back now
            resetEventConnectionSettingsFrame = new ManualResetEventSlim ();
            resetEventConnectionSettingsFrame.Reset ();
            if (!resetEventConnectionSettingsFrame.Wait (ConnectionTimeout)) {
                Disconnect ();
                throw new Exception ("Connection timed out");
            }
        }
开发者ID:Garciat,项目名称:HttpTwo,代码行数:58,代码来源:Http2Connection.cs

示例8: createClientStream

        protected override Stream createClientStream(string host, int port)
        {
            var rval = new SslStream(base.createClientStream(host, port), false, (o, cert, chain, errors) => true);

            //rval.AuthenticateAsClient(host);
            Task task = rval.AuthenticateAsClientAsync(host);
            task.Wait();

            return rval;
        }
开发者ID:gyantal,项目名称:SQLab,代码行数:10,代码来源:EClientSocketSSL.cs

示例9: ConnectAsync

 /// <summary>
 ///     Establishes a TCP connection with the endpoint at the specified address/port pair.
 /// </summary>
 /// <param name="address">The address of the endpoint to connect to.</param>
 /// <param name="port">The port of the endpoint to connect to.</param>
 /// <param name="secure">True to enable TLS on the socket.</param>
 public async Task ConnectAsync(string address, int port, bool secure = false)
 {
     await _backingTcpClient.ConnectAsync(address, port);
     InitializeWriteStream();
     if (secure)
     {
         var secureStream = new SslStream(_writeStream, true, (sender, cert, chain, sslPolicy) => ServerValidationCallback(sender, cert, chain, sslPolicy));
         await secureStream.AuthenticateAsClientAsync(address, null, System.Security.Authentication.SslProtocols.Tls, false);
         _secureStream = secureStream;
     }            
 }
开发者ID:whztt07,项目名称:xenko,代码行数:17,代码来源:TcpSocketClient.cs

示例10: OnRunJobAsync

		} // proc OnRunJob

		private async Task OnRunJobAsync()
		{
			inConnectionPhase = true;
			try
			{
				var timeoutSource = new CancellationTokenSource(30000);

				// resolve end point
				var serverTcp = this.GetService<IServerTcp>(true);
				if (endPoint == null)
					endPoint = await serverTcp.ResolveEndpointAsync(targetHost, targetPort, timeoutSource.Token);

				// register the connection
				if (endPoint != null)
				{
					var protocol = this.GetService<OdetteFileTransferProtocolItem>(true);

					// check if the protocol is running
					if (protocol.IsActiveProtocol(ChannelName))
						Log.Info("Protocol is already active.");
					else // create the connection
						try
						{
							var stream = await serverTcp.CreateConnectionAsync(endPoint, timeoutSource.Token);

							if (useSsl)
							{
								var ssl = new SslStream(stream, false, SslRemoteCertificateValidateCallback); // , SslLocalCertificateSelector
								await ssl.AuthenticateAsClientAsync(targetHost);

								var cert = ssl.RemoteCertificate;
								Log.Info($"Ssl active: auth={ssl.IsAuthenticated}, encrypt={ssl.IsEncrypted}, signed={ssl.IsSigned}\nissuer={cert.Issuer}\nsubject={cert.Subject}");
								stream = ssl;
							}

							await protocol.StartProtocolAsync(new OdetteNetworkStream(stream, channelName, Config), true);
						}
						catch (Exception e)
						{
							Log.Except("Connection failed.", e);
						}
				}
			}
			catch (Exception e)
			{
				Log.Except(e);
			}
			finally
			{
				inConnectionPhase = false;
			}
		} // proc OnRunJobAsync
开发者ID:twdes,项目名称:odette,代码行数:54,代码来源:OdetteConnectTcp.cs

示例11: CreateStream

        private async Task<Stream> CreateStream(Uri uri, Socket socket)
        {
            Stream stream = new NetworkStream(socket);

            if (uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
            {
                var sslStream = new SslStream(stream);
                await sslStream.AuthenticateAsClientAsync(uri.Host, new X509CertificateCollection(), _sslProtocols, checkCertificateRevocation: false);
                stream = sslStream;
            }

            return stream;
        }
开发者ID:jango2015,项目名称:OwinHttpClient,代码行数:13,代码来源:NetworkStreamFactory.cs

示例12: ConnectTls

 public async Task<ConnectStatus> ConnectTls ()
 {
     try {
         SslStream ssl = new SslStream(tcpc.GetStream(), false, CertificateValidationCallBack);
         await ssl.AuthenticateAsClientAsync(host);
         stream = ssl;
         return ConnectStatus.Ok;
     }
     catch
     {
         return ConnectStatus.Failed;
     }
 }
开发者ID:gregtatcam,项目名称:email_proc,代码行数:13,代码来源:ImapConnect.cs

示例13: TcpClient

 async Task<Stream> IConnectionFactory.Connect(string hostname, int port, bool useSsl)
 {
     TcpClient client = new TcpClient();
     client.NoDelay = true;
     await client.ConnectAsync(hostname, port);
     if (useSsl)
     {
         SslStream sslStream = new SslStream(client.GetStream());
         await sslStream.AuthenticateAsClientAsync(hostname);
         return sslStream;
     }
     return client.GetStream();
 }
开发者ID:Alxandr,项目名称:dotRant,代码行数:13,代码来源:IrcConnectionFactory.cs

示例14: GetNetworkStream

        protected override async Task<Stream> GetNetworkStream(TcpClient client)
        {
            var sslStream = new SslStream(
                client.GetStream(),
                false,
                ValidateServerCertificate,
                null
                );

            await sslStream.AuthenticateAsClientAsync(Hostname).ConfigureAwait(false);

            return sslStream;
        }
开发者ID:Homesnap,项目名称:loggly-csharp,代码行数:13,代码来源:SyslogSecureTransport.cs

示例15: Connect

        private async Task Connect()
        {
            try
            {
                // Could be a reconnect - get rid of the old stream if so
                if (_stream != null)
                {
                    _stream.Dispose();
                    _stream = null;
                }

                await _tcpClient.ConnectAsync(_host, _port);

                _stream = _tcpClient.GetStream();
                _stream.ReadTimeout = _configuration.WaitForDataTimeoutInMilliseconds;

                if (_configuration.Ssl)
                {
                    var sslStream = new SslStream(_stream, false, _configuration.CertificateValidationCallback);
                    await sslStream.AuthenticateAsClientAsync(_host);
                    _stream = sslStream;
                }

                if (_configuration.Password != null)
                {
                    var response = await Command.From("AUTH", _configuration.Password).SendAsync(this);

                    if (response.Value.IsError || response.Value.ToString() != "OK")
                        throw ExceptionBecause.Connection.FailedToAuthenticate(response);
                }

                _configuration.Events.OnConnectionOpened(new ConnectionEventArgs
                {
                    Host = _host,
                    Port = _port
                });
            }
            catch (Exception e)
            {
                _configuration.Events.OnConnectionError(new ConnectionEventArgs
                {
                    Host = _host,
                    Port = _port,
                    Exception = e
                });

                throw;
            }
        }
开发者ID:searbe,项目名称:redis-client,代码行数:49,代码来源:Connection.cs


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