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


C# SslStream类代码示例

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


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

示例1: Main

	static void Main(string[] args)
	{
		string host = "localhost";
		if (args.Length > 0)
			host = args[0];

		SslProtocols protocol = SslProtocols.Tls;
		if (args.Length > 1) {
			switch (args [1].ToUpper ()) {
			case "SSL":
				protocol = SslProtocols.Ssl3;
				break;
			}
		}

		X509CertificateCollection certificates = null;
		if (args.Length > 2) {
			string password = null;
			if (args.Length > 3)
				password = args [3];

			p12 = Mono.Security.X509.PKCS12.LoadFromFile(args [2], password);

			certificates = new X509CertificateCollection ();
			foreach (Mono.Security.X509.X509Certificate cert in p12.Certificates) {
				certificates.Add(new X509Certificate2(args [2], password));
				break;
			}
		}

		TcpClient client = new TcpClient ();
		client.Connect (host, 4433);
 
 		SslStream ssl = new SslStream (client.GetStream(), false, new RemoteCertificateValidationCallback (CertificateValidation), new LocalCertificateSelectionCallback (ClientCertificateSelection));

		ssl.AuthenticateAsClient (host, certificates, protocol, false); 	
		StreamWriter sw = new StreamWriter (ssl, System.Text.Encoding.ASCII);
		sw.WriteLine ("GET /clientcert.aspx{0}", Environment.NewLine);
		sw.Flush ();

		StreamReader sr = new StreamReader (ssl);
		Console.WriteLine (sr.ReadToEnd ());
	}
开发者ID:nlhepler,项目名称:mono,代码行数:43,代码来源:mutual.cs

示例2: 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

示例3: SslStream_StreamToStream_Successive_ClientWrite_Sync_Success

        public void SslStream_StreamToStream_Successive_ClientWrite_Sync_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.");

                clientSslStream.Write(_sampleMsg);

                serverSslStream.Read(recvBuf, 0, _sampleMsg.Length);

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

                clientSslStream.Write(_sampleMsg);

                serverSslStream.Read(recvBuf, 0, _sampleMsg.Length);

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

示例4: SSLAuthenticateTest

    void SSLAuthenticateTest()
    {
        var client = new TcpClient ();
        String hosturl = "115.239.211.112";//www.baidu.com;
        client.Connect (hosturl, 443);

        using (var stream = client.GetStream ())
        {
            Debug.Log("CONNECTING ");
            var ostream = stream as Stream;
            if (true)
            {
                ostream = new SslStream (stream, false, new RemoteCertificateValidationCallback (ValidateServerCertificate));

                try
                {
                    var ssl = ostream as SslStream;
                    ssl.AuthenticateAsClient (hosturl);
                }
                catch (Exception e)
                {
                    Debug.Log ("Exception: " + e.Message);
                }
            }
        }
    }
开发者ID:xfanhsl,项目名称:IL2CPP_Test,代码行数:26,代码来源:IL2CPPCompatible.cs

示例5: SslStream_StreamToStream_Successive_ClientWrite_Success

        public void SslStream_StreamToStream_Successive_ClientWrite_Success()
        {
            byte[] recvBuf = new byte[sampleMsg.Length];
            MockNetwork network = new MockNetwork();

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

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

                clientSslStream.Write(sampleMsg);

                serverSslStream.Read(recvBuf, 0, sampleMsg.Length);

                clientSslStream.Write(sampleMsg);

                // TODO Issue#3802
                // The condition on which read method (UpdateReadStream) in FakeNetworkStream does a network read is flawed.
                // That works fine in single read/write but fails in multi read write as stream size can be more, but real data can be < stream size.
                // So I am doing an explicit read here. This issue is specific to test only & irrespective of xplat.
                serverStream.DoNetworkRead();

                serverSslStream.Read(recvBuf, 0, sampleMsg.Length);

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

示例6: ServerNoEncryption_ClientNoEncryption_ConnectWithNoEncryption

        public async Task ServerNoEncryption_ClientNoEncryption_ConnectWithNoEncryption()
        {
            using (var serverNoEncryption = new DummyTcpServer(
                new IPEndPoint(IPAddress.Loopback, 0), EncryptionPolicy.NoEncryption))
            using (var client = new TcpClient())
            {
                await client.ConnectAsync(serverNoEncryption.RemoteEndPoint.Address, serverNoEncryption.RemoteEndPoint.Port);

                using (var sslStream = new SslStream(client.GetStream(), false, AllowAnyServerCertificate, null, EncryptionPolicy.NoEncryption))
                {
                    if (SupportsNullEncryption)
                    {
                        await sslStream.AuthenticateAsClientAsync("localhost", null, SslProtocolSupport.DefaultSslProtocols, false);
                        _log.WriteLine("Client authenticated to server({0}) with encryption cipher: {1} {2}-bit strength",
                            serverNoEncryption.RemoteEndPoint, sslStream.CipherAlgorithm, sslStream.CipherStrength);

                        CipherAlgorithmType expected = CipherAlgorithmType.Null;
                        Assert.Equal(expected, sslStream.CipherAlgorithm);
                        Assert.Equal(0, sslStream.CipherStrength);
                    }
                    else
                    {
                        var ae = await Assert.ThrowsAsync<AuthenticationException>(() => sslStream.AuthenticateAsClientAsync("localhost", null, SslProtocolSupport.DefaultSslProtocols, false));
                        Assert.IsType<PlatformNotSupportedException>(ae.InnerException);
                    }
                }
            }
        }
开发者ID:ChuangYang,项目名称:corefx,代码行数:28,代码来源:ServerNoEncryptionTest.cs

示例7: 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

示例8: WebSocketClient

	//Encryption
	internal WebSocketClient(Socket s,X509Certificate cert)
	{	
		this.Socket = s;
		var ns = new NetworkStream(s,false);
		var ss = new SslStream(ns, false);
		ss.AuthenticateAsServer(cert,false,SslProtocols.Tls12,false);
		this.stream = ss;
	}
开发者ID:Carrot031,项目名称:websocket-cs,代码行数:9,代码来源:WebSocketClient.cs

示例9: SslStream_AuthenticateAsClient_AllSupported_Success

 public async Task SslStream_AuthenticateAsClient_AllSupported_Success()
 {
     SslStream stream = new SslStream(new FakeStream());
     await stream.AuthenticateAsClientAsync(
         "host",
         null,
         SslProtocolSupport.SupportedSslProtocols,
         false);
 }
开发者ID:Rayislandstyle,项目名称:corefx,代码行数:9,代码来源:SslStreamAllowedProtocolsTest.cs

示例10: 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

示例11: TestBase

            public TestBase()
            {
                var network = new VirtualNetwork();
                var clientNet = new VirtualNetworkStream(network, false);
                var serverNet = new VirtualNetworkStream(network, true);

                _clientStream = new SslStream(clientNet, false, AllowAnyServerCertificate);
                _serverStream = new SslStream(serverNet, false, AllowAnyServerCertificate);
            }
开发者ID:dotnet,项目名称:corefx,代码行数:9,代码来源:SslStreamSystemDefaultsTest.cs

示例12: CertificateValidationClientServer_EndToEnd_Ok

        public async Task CertificateValidationClientServer_EndToEnd_Ok()
        {
            IPEndPoint endPoint = new IPEndPoint(IPAddress.IPv6Loopback, 0);
            var server = new TcpListener(endPoint);
            server.Start();

            using (var clientConnection = new TcpClient(AddressFamily.InterNetworkV6))
            {
                IPEndPoint serverEndPoint = (IPEndPoint)server.LocalEndpoint;

                Task clientConnect = clientConnection.ConnectAsync(serverEndPoint.Address, serverEndPoint.Port);
                Task<TcpClient> serverAccept = server.AcceptTcpClientAsync();

                Assert.True(
                    Task.WaitAll(
                        new Task[] { clientConnect, serverAccept }, 
                        TestConfiguration.TestTimeoutSeconds * 1000),
                    "Client/Server TCP Connect timed out.");

                using (TcpClient serverConnection = await serverAccept)
                using (SslStream sslClientStream = new SslStream(
                    clientConnection.GetStream(),
                    false,
                    ClientSideRemoteServerCertificateValidation))
                using (SslStream sslServerStream = new SslStream(
                    serverConnection.GetStream(),
                    false,
                    ServerSideRemoteClientCertificateValidation))

                {
                    string serverName = _serverCertificate.GetNameInfo(X509NameType.SimpleName, false);
                    string clientName = _clientCertificate.GetNameInfo(X509NameType.SimpleName, false);

                    var clientCerts = new X509CertificateCollection();
                    clientCerts.Add(_clientCertificate);

                    Task clientAuthentication = sslClientStream.AuthenticateAsClientAsync(
                        serverName,
                        clientCerts,
                        TestConfiguration.DefaultSslProtocols,
                        false);

                    Task serverAuthentication = sslServerStream.AuthenticateAsServerAsync(
                        _serverCertificate,
                        true,
                        TestConfiguration.DefaultSslProtocols,
                        false);

                    Assert.True(
                        Task.WaitAll(
                            new Task[] { clientAuthentication, serverAuthentication }, 
                            TestConfiguration.TestTimeoutSeconds * 1000),
                        "Client/Server Authentication timed out.");
                }
            }
        }
开发者ID:mmajcica,项目名称:corefx,代码行数:56,代码来源:CertificateValidationClientServer.cs

示例13: SslStream_AuthenticateAsClient_AllUnsuported_Fails

 public async Task SslStream_AuthenticateAsClient_AllUnsuported_Fails()
 {
     SslStream stream = new SslStream(new FakeStream());
     await Assert.ThrowsAsync<NotSupportedException>(
         () => stream.AuthenticateAsClientAsync(
             "host",
             null,
             SslProtocolSupport.UnsupportedSslProtocols,
             false));
 }
开发者ID:Rayislandstyle,项目名称:corefx,代码行数:10,代码来源:SslStreamAllowedProtocolsTest.cs

示例14: CertificateValidationRemoteServer_EndToEnd_Ok

        public async Task CertificateValidationRemoteServer_EndToEnd_Ok()
        {
            using (var client = new TcpClient(AddressFamily.InterNetwork))
            {
                await client.ConnectAsync(TestSettings.Http.SecureHost, 443);

                using (SslStream sslStream = new SslStream(client.GetStream(), false, RemoteHttpsCertValidation, null))
                {
                    await sslStream.AuthenticateAsClientAsync(TestSettings.Http.SecureHost);
                }
            }
        }
开发者ID:charygao,项目名称:corefx,代码行数:12,代码来源:CertificateValidationRemoteServer.cs

示例15: CertificateValidationRemoteServer_EndToEnd_Ok

        public async Task CertificateValidationRemoteServer_EndToEnd_Ok()
        {
            using (var client = new TcpClient(AddressFamily.InterNetwork))
            {
                await client.ConnectAsync(Configuration.Security.TlsServer.IdnHost, Configuration.Security.TlsServer.Port);

                using (SslStream sslStream = new SslStream(client.GetStream(), false, RemoteHttpsCertValidation, null))
                {
                    await sslStream.AuthenticateAsClientAsync(Configuration.Security.TlsServer.IdnHost);
                }
            }
        }
开发者ID:dotnet,项目名称:corefx,代码行数:12,代码来源:CertificateValidationRemoteServer.cs


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