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


C# SslStream.AuthenticateAsServerAsync方法代码示例

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


在下文中一共展示了SslStream.AuthenticateAsServerAsync方法的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: FinishAccept

 public void FinishAccept(byte[] buffer, int offset, int length, IPEndPoint remoteEndPoint, IPEndPoint localEndPoint)
 {
     _remoteEndPoint = remoteEndPoint;
     _localEndPoint = localEndPoint;
     Debug.Assert(length == 0);
     try
     {
         _ssl = new SslStream(_inputStream, true);
         _authenticateTask = _ssl.AuthenticateAsServerAsync(_serverCertificate, false, _protocols, false).ContinueWith((t, selfObject) =>
         {
             var self = (SslTransportHandler)selfObject;
             if (t.IsFaulted || t.IsCanceled)
                 self._next.FinishAccept(null, 0, 0, null, null);
             else
                 self._ssl.ReadAsync(self._recvBuffer, self._recvOffset, self._recvLength).ContinueWith((t2, selfObject2) =>
                 {
                     var self2 = (SslTransportHandler)selfObject2;
                     if (t2.IsFaulted || t2.IsCanceled)
                         self2._next.FinishAccept(null, 0, 0, null, null);
                     else
                         self2._next.FinishAccept(self2._recvBuffer, self2._recvOffset, t2.Result, self2._remoteEndPoint, self2._localEndPoint);
                 }, self);
         }, this);
     }
     catch (Exception)
     {
         Callback.StartDisconnect();
     }
 }
开发者ID:Erwinvandervalk,项目名称:Nowin,代码行数:29,代码来源:SslTransportHandler.cs

示例3: For

        async public static Task<ProxySslRequest> For(ProxyRequest wrapperRequest, IRequestInspector wrapperRequestInspector)
        {
            if (_certProvider == null)
            {
                _certProvider = new CertificateProvider(MakeCertPath);
                _certProvider.EnsureRootCertificate();
            }

            var sslRequest = new ProxySslRequest
                {
                    WrapperRequest = wrapperRequest,
                    ClientPid = wrapperRequest.ClientPid,
                    ClientSocket = wrapperRequest.ClientSocket,
                    ClientStream = wrapperRequest.ClientStream
                };

            if (wrapperRequestInspector != null)
                wrapperRequestInspector.OnTransferredToSecureRequest(sslRequest);

            var hostName = sslRequest.GetHostName();
            sslRequest._hostCert = _certProvider.GetCertificateForHost(hostName);

            var clientSsslStream = new SslStream(wrapperRequest.ClientStream, true, RemoteCertificateValidator, sslRequest.LocalCertificateSelector);
            await clientSsslStream.AuthenticateAsServerAsync(sslRequest._hostCert);
            sslRequest.SecureClientStream = clientSsslStream;

            sslRequest.ReadPrologue();

            return sslRequest;
        }
开发者ID:swsmile,项目名称:SharpProxy,代码行数:30,代码来源:ProxySslRequest.cs

示例4: CreateSession

        internal override async Task<HttpSession> CreateSession(long sessionId, TcpClient client)
        {
            var sslStream = new SslStream(client.GetStream());
            await sslStream.AuthenticateAsServerAsync(serverCertificate, false, sslProtocols, false).ConfigureAwait(false);

            return new HttpSession(sessionId, client, sslStream, true, maxKeepAlives, sessionReadBufferSize, (int)sessionReadTimeout.TotalMilliseconds, (int)sessionWriteTimeout.TotalMilliseconds);
        }
开发者ID:joongonn,项目名称:mHttp,代码行数:7,代码来源:HttpsBackend.cs

示例5: ProcessAsync

        public async Task ProcessAsync(IConnection connection, SmtpCommand command)
        {
            X509Certificate certificate = connection.Server.Behaviour.GetSSLCertificate(connection);

            if (certificate == null)
            {
                await connection.WriteResponseAsync(new SmtpResponse(StandardSmtpResponseCode.CommandNotImplemented, "TLS configuration error - no certificate"));
                return;
            }

            await connection.WriteResponseAsync(new SmtpResponse(StandardSmtpResponseCode.ServiceReady,
                                                      "Ready to start TLS"));

#pragma warning disable 0618
            var sslProtos = SslProtocols.Ssl2 | SslProtocols.Ssl3 | SslProtocols.Tls;
#pragma warning restore 0618

            await connection.ApplyStreamFilterAsync(async stream =>
                                                     {
                                                         SslStream sslStream = new SslStream(stream);
                                                         await sslStream.AuthenticateAsServerAsync(certificate
                                                             , false,
                                                             sslProtos,
                                                             false);
                                                         return sslStream;
                                                     });

            connection.Session.SecureConnection = true;
        }
开发者ID:rnwood,项目名称:smtp4dev,代码行数:29,代码来源:StartTlsVerb.cs

示例6: AuthenticateAsync

        public async Task AuthenticateAsync(X509Certificate2 certificate)
        {
            if (certificate == null)
                return;

            SslStream sslStream = new SslStream(Stream, false);
            Stream = sslStream;
            await sslStream.AuthenticateAsServerAsync(certificate);   
        }
开发者ID:IRlyDontKnow,项目名称:websocketproxy,代码行数:9,代码来源:TcpHost.cs

示例7: Invoke

        public async Task Invoke(TcpContext context)
        {
            var sslStream = new SslStream(context.Body);

            await sslStream.AuthenticateAsServerAsync(_cert);

            context.Body = sslStream;

            await _next(context);
        }
开发者ID:davidfowl,项目名称:ServerStack,代码行数:10,代码来源:TlsMiddleware.cs

示例8: ExecuteAsync

        /// <summary>
        /// Execute the command.
        /// </summary>
        /// <param name="context">The execution context to operate on.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>A task which asynchronously performs the execution.</returns>
        public override async Task ExecuteAsync(ISmtpSessionContext context, CancellationToken cancellationToken)
        {
            await context.Text.ReplyAsync(SmtpResponse.ServiceReady, cancellationToken);

            var stream = new SslStream(context.Text.GetInnerStream(), true);

            await stream.AuthenticateAsServerAsync(_certificate, false, SslProtocols.Default, true);

            context.Text = new NetworkTextStream(stream);
        }
开发者ID:cosullivan,项目名称:SmtpServer,代码行数:16,代码来源:StartTlsCommand.cs

示例9: ExtendConnection

        public Stream ExtendConnection(Stream stream)
        {
            var ssl = new SslStream(stream, false, _validation);
#if (UAP10_0 || DOTNET5_4 || NETSTANDARD || NETSTANDARDAPP1_5)
            ssl.AuthenticateAsServerAsync(_certificate, _validation != null, SslProtocols.Tls12, false).Wait();
#else
            ssl.AuthenticateAsServer(_certificate, _validation != null, SslProtocols.Tls12, false);
#endif
            return ssl;
        }
开发者ID:papci,项目名称:WebSocketListener,代码行数:10,代码来源:WebSocketSecureConnectionExtension.cs

示例10: OnConnection

        public async Task OnConnection(ConnectionFilterContext context)
        {
            await _previous.OnConnection(context);

            if (string.Equals(context.Address.Scheme, "https", StringComparison.OrdinalIgnoreCase))
            {
                var sslStream = new SslStream(context.Connection);
                await sslStream.AuthenticateAsServerAsync(_cert);
                context.Connection = sslStream;
            }
        }
开发者ID:Starcounter,项目名称:KestrelHttpServer,代码行数:11,代码来源:HttpsConnectionFilter.cs

示例11: CreateSession

        internal override async Task<HttpSession> CreateSession(long sessionId,
                                                                TcpClient client,
                                                                int _maxKeepAlives,
                                                                int _sessionReadBufferSize,
                                                                TimeSpan _sessionReadTimeout,
                                                                TimeSpan _sessionWriteTimeout)
        {
            var sslStream = new SslStream(client.GetStream());
            await sslStream.AuthenticateAsServerAsync(serverCertificate, false, sslProtocols, false);

            return new HttpSession(sessionId, client, sslStream, true, _maxKeepAlives, _sessionReadBufferSize, _sessionReadTimeout, _sessionWriteTimeout);
        }
开发者ID:CubeCoders,项目名称:mHttp,代码行数:12,代码来源:HttpsBackend.cs

示例12: Accept

        public override async void Accept()
        {
            try
            {
                if (Sockets[0].AcceptSocket != null)
                {
                    networkStream = new NetworkStream(Sockets[0].AcceptSocket);
                    tlsStream = new SslStream(networkStream, false);
                    tlsSemaphore = new SemaphoreSlim(1, 1);

                    await tlsStream.AuthenticateAsServerAsync(Manager.Session.Certificate, false, SslProtocols.Tls12, false);

                    if (tlsStream.IsAuthenticated && Manager.Session.Add(this))
                    {
                        var buffer = Sockets[0].Buffer;
                        int numReadBytes;

                        do
                        {
                            numReadBytes = await tlsStream.ReadAsync(buffer, 0, buffer.Length);

                            if (numReadBytes == 0)
                                break;

                            var headerLength = (buffer[0] << 8) | buffer[1];
                            var header = Header.Parser.ParseFrom(new CodedInputStream(buffer, 2, headerLength));
                            var data = new byte[header.Size];

                            if (header.Size > 0)
                                Buffer.BlockCopy(buffer, 2 + headerLength, data, 0, data.Length);

                            await Manager.BnetPacket.CallHandler(header, data, this);
                        } while (numReadBytes != 0);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Message(LogTypes.Error, ex.Message);
            }
            finally
            {
                if (Manager.Session.Remove(this))
                    Dispose();
            }
        }
开发者ID:Arctium-Emulation,项目名称:Project-WoW,代码行数:46,代码来源:BnetSession.cs

示例13: FinishAccept

 public void FinishAccept(byte[] buffer, int offset, int length, IPEndPoint remoteEndPoint, IPEndPoint localEndPoint)
 {
     Debug.Assert(length == 0);
     try
     {
         _ssl = new SslStream(_inputStream, true);
         _authenticateTask = _ssl.AuthenticateAsServerAsync(_serverParameters.Certificate, _serverParameters.ClientCertificateRequired, _serverParameters.Protocols, false).ContinueWith((t, selfObject) =>
           {
               var self = (SslTransportHandler)selfObject;
               self._next.SetRemoteCertificate(_ssl.RemoteCertificate);
           }, this, TaskContinuationOptions.OnlyOnRanToCompletion);
         _next.FinishAccept(_recvBuffer, _recvOffset, 0, remoteEndPoint, localEndPoint);
     }
     catch (Exception)
     {
         Callback.StartDisconnect();
     }
 }
开发者ID:Bobris,项目名称:Nowin,代码行数:18,代码来源:SslTransportHandler.cs

示例14: DesktopNetworkStream

        /// <summary>
        /// Initializes a server instance of <see cref="DesktopNetworkStream"/>.
        /// </summary>
        /// <param name="tcpClient">TCP client.</param>
        /// <param name="certificate">Certificate for authenticated connection.</param>
        /// <remarks>Ownership of <paramref name="tcpClient"/> remains with the caller, including responsibility for
        /// disposal. Therefore, a handle to <paramref name="tcpClient"/> is <em>not</em> stored when <see cref="DesktopNetworkStream"/>
        /// is initialized with this server-side constructor.</remarks>
        internal DesktopNetworkStream(TcpClient tcpClient, X509Certificate certificate)
        {
            this.Host = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address.ToString();
            this.Port = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Port;

            Stream stream = tcpClient.GetStream();
            if (certificate != null)
            {
                var ssl = new SslStream(stream, false);
#if NETSTANDARD
                ssl.AuthenticateAsServerAsync(certificate, false, SslProtocols.Tls, false).Wait();
#else
                ssl.AuthenticateAsServer(certificate, false, SslProtocols.Tls, false);
#endif
                stream = ssl;
            }

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

示例15: InitializeConnectionAsync

		async protected override Task InitializeConnectionAsync(TcpSocket Client)
		{
			var Stream = new SslStream(
				innerStream: Client.Stream,
				leaveInnerStreamOpen: false,
				userCertificateValidationCallback: (Sender, Certificate, Chain, SslPolicyErrors) =>
				{
					//Console.WriteLine("userCertificateValidationCallback");
					return true;
				},
				userCertificateSelectionCallback: (Sender, TargetHost, LocalCertificates, RemoteCertificate, AcceptableIssuers) =>
				{
					//Console.WriteLine("Host: '{0}'", targetHost);
					//Console.WriteLine(String.Join(",", acceptableIssuers));

					if (HostCertificates.ContainsKey(TargetHost))
					{
						return HostCertificates[TargetHost];
					}
					else
					{
						return DefaultX509Certificate;
					}
				}
			);
			await Stream.AuthenticateAsServerAsync(DefaultX509Certificate);

			//await Stream.AuthenticateAsServerAsync(X509Certificate, true, SslProtocols.Tls, true);
			Client.UnsafeSetStream(Stream);
		}
开发者ID:soywiz,项目名称:NodeNetAsync,代码行数:30,代码来源:HttpsServer.cs


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