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


C# SslStream.ReadAsync方法代码示例

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


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

示例1: SslStream_StreamToStream_ServerInitiatedCloseNotify_Ok

        public async Task SslStream_StreamToStream_ServerInitiatedCloseNotify_Ok()
        {
            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
            using (var serverStream = new VirtualNetworkStream(network, isServer: true))
            using (var client = new SslStream(clientStream, true, AllowAnyServerCertificate))
            using (var server = new SslStream(serverStream))
            using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate())
            {
                var handshake = new Task[2];

                handshake[0] = server.AuthenticateAsServerAsync(certificate);
                handshake[1] = client.AuthenticateAsClientAsync(certificate.GetNameInfo(X509NameType.SimpleName, false));

                await Task.WhenAll(handshake).TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);

                var readBuffer = new byte[1024];

                await server.ShutdownAsync();
                int bytesRead = await client.ReadAsync(readBuffer, 0, readBuffer.Length);
                // close_notify received by the client.
                Assert.Equal(0, bytesRead);

                await client.ShutdownAsync();
                bytesRead = await server.ReadAsync(readBuffer, 0, readBuffer.Length);
                // close_notify received by the server.
                Assert.Equal(0, bytesRead);
            }
        }
开发者ID:dotnet,项目名称:corefx,代码行数:30,代码来源:SslStreamAlertsTest.cs

示例2: SslStream_StreamToStream_HandshakeAlert_Ok

        public async Task SslStream_StreamToStream_HandshakeAlert_Ok()
        {
            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
            using (var serverStream = new VirtualNetworkStream(network, isServer: true))
            using (var client = new SslStream(clientStream, true, AllowAnyServerCertificate))
            using (var server = new SslStream(serverStream, true, FailClientCertificate))
            using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate())
            {
                Task serverAuth = server.AuthenticateAsServerAsync(certificate);
                await client.AuthenticateAsClientAsync(certificate.GetNameInfo(X509NameType.SimpleName, false));

                byte[] buffer = new byte[1024];

                // Schannel semantics require that Decrypt is called to receive an alert.
                await client.WriteAsync(buffer, 0, buffer.Length);
                var exception = await Assert.ThrowsAsync<IOException>(() => client.ReadAsync(buffer, 0, buffer.Length));

                Assert.IsType<Win32Exception>(exception.InnerException);
                var win32ex = (Win32Exception)exception.InnerException;

                // The Schannel HResults for each alert are documented here: 
                // https://msdn.microsoft.com/en-us/library/windows/desktop/dd721886(v=vs.85).aspx
                Assert.Equal(SEC_E_CERT_UNKNOWN, (uint)win32ex.NativeErrorCode);

                await Assert.ThrowsAsync<AuthenticationException>(() => serverAuth);

                await Assert.ThrowsAsync<AuthenticationException>(() => server.WriteAsync(buffer, 0, buffer.Length));
                await Assert.ThrowsAsync<AuthenticationException>(() => server.ReadAsync(buffer, 0, buffer.Length));
            }
        }
开发者ID:dotnet,项目名称:corefx,代码行数:32,代码来源:SslStreamAlertsTest.cs

示例3: SslStream_SendReceiveOverNetworkStream_Ok

        public async void SslStream_SendReceiveOverNetworkStream_Ok()
        {
            TcpListener listener = new TcpListener(IPAddress.Any, 0);

            using (X509Certificate2 serverCertificate = Configuration.Certificates.GetServerCertificate())
            using (TcpClient client = new TcpClient())
            {
                listener.Start();

                Task clientConnectTask = client.ConnectAsync(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port);
                Task<TcpClient> listenerAcceptTask = listener.AcceptTcpClientAsync();

                await Task.WhenAll(clientConnectTask, listenerAcceptTask);

                TcpClient server = listenerAcceptTask.Result;
                using (SslStream clientStream = new SslStream(
                    client.GetStream(),
                    false,
                    new RemoteCertificateValidationCallback(ValidateServerCertificate),
                    null,
                    EncryptionPolicy.RequireEncryption))
                using (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);

                    await Task.WhenAll(clientAuthenticationTask, serverAuthenticationTask);

                    byte[] readBuffer = new byte[256];
                    Task<int> readTask = clientStream.ReadAsync(readBuffer, 0, readBuffer.Length);

                    byte[] writeBuffer = new byte[256];
                    Task writeTask = clientStream.WriteAsync(writeBuffer, 0, writeBuffer.Length);

                    bool result = Task.WaitAll(
                        new Task[1] { writeTask }, 
                        TestConfiguration.PassingTestTimeoutMilliseconds);

                    Assert.True(result, "WriteAsync timed-out.");
                }
            }
        }
开发者ID:ESgarbi,项目名称:corefx,代码行数:57,代码来源:SslStreamNetworkStreamTest.cs

示例4: SslStream_StreamToStream_Successive_ClientWrite_Async_Success

        public void SslStream_StreamToStream_Successive_ClientWrite_Async_Success()
        {
            byte[] recvBuf = new byte[_sampleMsg.Length];
            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
            using (var serverStream = new VirtualNetworkStream(network, isServer: true))
            using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
            using (var serverSslStream = new SslStream(serverStream))
            {
                bool result = DoHandshake(clientSslStream, serverSslStream);

                Assert.True(result, "Handshake completed.");

                Task[] tasks = new Task[2];

                tasks[0] = serverSslStream.ReadAsync(recvBuf, 0, _sampleMsg.Length);
                tasks[1] = clientSslStream.WriteAsync(_sampleMsg, 0, _sampleMsg.Length);
                bool finished = Task.WaitAll(tasks, TestConfiguration.PassingTestTimeoutMilliseconds);
                Assert.True(finished, "Send/receive completed in the allotted time");
                Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify first read data is as expected.");

                tasks[0] = serverSslStream.ReadAsync(recvBuf, 0, _sampleMsg.Length);
                tasks[1] = clientSslStream.WriteAsync(_sampleMsg, 0, _sampleMsg.Length);
                finished = Task.WaitAll(tasks, TestConfiguration.PassingTestTimeoutMilliseconds);
                Assert.True(finished, "Send/receive completed in the allotted time");
                Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify second read data is as expected.");
            }
        }
开发者ID:benpye,项目名称:corefx,代码行数:29,代码来源:SslStreamStreamToStreamTest.cs

示例5: RunTest

            public async Task RunTest()
            {
                using (var tcp = new TcpClient())
                {
                    _log.WriteLine("[Client] Connecting to {0}:{1}", _server, _port);
                    await tcp.ConnectAsync(_server, _port);
                    using (var tls = new SslStream(tcp.GetStream(), false, CertificateValidation))
                    {
                        _log.WriteLine("[Client] Connected. Authenticating...");
                        await tls.AuthenticateAsClientAsync(_server, null, System.Security.Authentication.SslProtocols.Tls, false);

                        string requestString = "GET / HTTP/1.0\r\nHost: servername.test.contoso.com\r\nUser-Agent: Testing application\r\n\r\n";
                        byte[] requestBuffer = Encoding.UTF8.GetBytes(requestString);

                        _log.WriteLine("[Client] Sending request ({0} Bytes)", requestBuffer.Length);

                        await tls.WriteAsync(requestBuffer, 0, requestBuffer.Length);

                        _log.WriteLine("[Client] Waiting for reply...");

                        int bytesRead = 0;
                        int chunks = 0;
                        do
                        {
                            byte[] responseBuffer = new byte[2048];
                            bytesRead = await tls.ReadAsync(responseBuffer, 0, responseBuffer.Length);

                            if (bytesRead > 0)
                            {
                                string responseString = Encoding.UTF8.GetString(responseBuffer, 0, bytesRead);
                                _log.WriteLine("[Client {0}: {2} Bytes] Response: <<<<<{1}>>>>>", chunks, responseString, bytesRead);
                            }

                            if (bytesRead == 1 && chunks == 0)
                            {
                                AuxRecordDetected = true;
                            }

                            chunks++;
                        }
                        while (bytesRead > 0);
                    }
                }
            }
开发者ID:alessandromontividiu03,项目名称:corefx,代码行数:44,代码来源:SslStreamSchSendAuxRecordTest.cs

示例6: SslStream_StreamToStream_Successive_ClientWrite_Async_Success

        public async Task SslStream_StreamToStream_Successive_ClientWrite_Async_Success()
        {
            byte[] recvBuf = new byte[_sampleMsg.Length];
            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
            using (var serverStream = new VirtualNetworkStream(network, isServer: true))
            using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
            using (var serverSslStream = new SslStream(serverStream))
            {
                bool result = DoHandshake(clientSslStream, serverSslStream);

                Assert.True(result, "Handshake completed.");

                await clientSslStream.WriteAsync(_sampleMsg, 0, _sampleMsg.Length)
                    .TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);

                int bytesRead = 0;
                while (bytesRead < _sampleMsg.Length)
                {
                    bytesRead += await serverSslStream.ReadAsync(recvBuf, bytesRead, _sampleMsg.Length - bytesRead)
                        .TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);
                }

                Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify first read data is as expected.");

                await clientSslStream.WriteAsync(_sampleMsg, 0, _sampleMsg.Length)
                    .TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);

                bytesRead = 0;
                while (bytesRead < _sampleMsg.Length)
                {
                    bytesRead += await serverSslStream.ReadAsync(recvBuf, bytesRead, _sampleMsg.Length - bytesRead)
                        .TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);
                }

                Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify second read data is as expected.");
            }
        }
开发者ID:dotnet,项目名称:corefx,代码行数:39,代码来源:SslStreamStreamToStreamTest.cs

示例7: TestAsyncBasic

		public void TestAsyncBasic()
		{
			var listener = new TcpListener(IPAddress.Loopback, 0);
			listener.Start(5);
			var ep = (IPEndPoint)listener.LocalEndpoint;

			Console.WriteLine("Server> waiting for accept");

			listener.BeginAcceptTcpClient((IAsyncResult ar) =>
			{
				var client = listener.EndAcceptTcpClient(ar);

				var sslStream = new SslStream(client.GetStream(), false);
				Console.WriteLine("Server> authenticate");

				sslStream.BeginAuthenticateAsServer(_ctx.ServerCertificate, async (ar2) =>
				{
					sslStream.EndAuthenticateAsServer(ar2);

					Console.WriteLine("Server> CurrentCipher: {0}", sslStream.Ssl.CurrentCipher.Name);
					Assert.AreEqual("AES256-GCM-SHA384", sslStream.Ssl.CurrentCipher.Name);

					var buf = new byte[256];
					await sslStream.ReadAsync(buf, 0, buf.Length);
					Assert.AreEqual(clientMessage.ToString(), buf.ToString());

					await sslStream.WriteAsync(serverMessage, 0, serverMessage.Length);

					sslStream.Close();
					client.Close();

					Console.WriteLine("Server> done");
				}, null);
			}, null);

			var evtDone = new AutoResetEvent(false);

			var tcp = new TcpClient(AddressFamily.InterNetwork);
			tcp.BeginConnect(ep.Address.ToString(), ep.Port, (IAsyncResult ar) =>
			{
				tcp.EndConnect(ar);

				var sslStream = new SslStream(tcp.GetStream());
				Console.WriteLine("Client> authenticate");

				sslStream.BeginAuthenticateAsClient("localhost", async (ar2) =>
				{
					sslStream.EndAuthenticateAsClient(ar2);

					Console.WriteLine("Client> CurrentCipher: {0}", sslStream.Ssl.CurrentCipher.Name);
					Assert.AreEqual("AES256-GCM-SHA384", sslStream.Ssl.CurrentCipher.Name);

					await sslStream.WriteAsync(clientMessage, 0, clientMessage.Length);

					var buf = new byte[256];
					await sslStream.ReadAsync(buf, 0, buf.Length);
					Assert.AreEqual(serverMessage.ToString(), buf.ToString());

					sslStream.Close();
					tcp.Close();

					Console.WriteLine("Client> done");

					evtDone.Set();
				}, null);
			}, null);

			evtDone.WaitOne();
		}
开发者ID:yaobos,项目名称:openssl-net,代码行数:69,代码来源:TestSSL.cs

示例8: HttpConversation

        private async Task<bool> HttpConversation(SslStream tls)
        {
            int totalBytesRead = 0;
            int chunks = 0;

            while (totalBytesRead < 5)
            {
                var requestBuffer = new byte[2048];
                int bytesRead = await tls.ReadAsync(requestBuffer, 0, requestBuffer.Length);
                totalBytesRead += bytesRead;

                string requestString = Encoding.UTF8.GetString(requestBuffer, 0, bytesRead);

                _log.WriteLine("[Server] Received {0} bytes: <<<{1}>>>", bytesRead, requestString);
                if (bytesRead == 0)
                {
                    return false;
                }

                if (bytesRead == 1 && chunks == 0)
                {
                    AuxRecordDetected = true;
                }

                chunks++;
            }

            _log.WriteLine("[Server] Using cipher {0}", tls.CipherAlgorithm);

            // Test is inconclusive if any non-CBC cipher is used:
            if (tls.CipherAlgorithm == CipherAlgorithmType.None ||
                tls.CipherAlgorithm == CipherAlgorithmType.Null ||
                tls.CipherAlgorithm == CipherAlgorithmType.Rc4)
            {
                IsInconclusive = true;
            }

            byte[] responseBuffer = Encoding.UTF8.GetBytes(ResponseString);
            await tls.WriteAsync(responseBuffer, 0, responseBuffer.Length);
            _log.WriteLine("[Server] Replied with {0} bytes.", responseBuffer.Length);
            return true;
        }
开发者ID:ESgarbi,项目名称:corefx,代码行数:42,代码来源:SchSendAuxRecordTestServer.cs


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