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


C# Security.SslStream类代码示例

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


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

示例1: Client

        public Client(String host, Int32 port)
        {
            try
            {

                clientName = Dns.GetHostName();

            }
            catch (SocketException se)
            {

                MessageBox.Show("ERROR: Could not retrieve client's DNS hostname.  Please try again." + se.Message + ".", "Client Socket Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;

            }

            serverName = host;
            gamePort = port;
            client = new TcpClient(host, port);
            netStream = client.GetStream();
            reader = new StreamReader(netStream);
            writer = new StreamWriter(netStream);
            ssl = new SslStream(netStream, false, new RemoteCertificateValidationCallback(ValidateCert));
            cert = new X509Certificate2("server.crt");
            ssl.AuthenticateAsClient(serverName);
            writer.AutoFlush = true;
        }
开发者ID:Team7-SoftEng,项目名称:GateofGabethulu-launcher,代码行数:27,代码来源:Client.cs

示例2: ServerConnection

 public ServerConnection(TcpClient client, SslStream stream, BinaryReader binaryReader, BinaryWriter binaryWriter)
 {
     _client = client;
     _stream = stream;
     _binaryReader = binaryReader;
     _binaryWriter = binaryWriter;
 }
开发者ID:OrcusTechnologies,项目名称:Orcus.Plugins.ServerStressTest,代码行数:7,代码来源:ServerConnection.cs

示例3: Discover

        public ServiceEndPoint Discover(Uri remoteUri)
        {
            try
            {
                using (var client = CreateTcpClient())
                {
                    client.ConnectWithTimeout(remoteUri, HalibutLimits.TcpClientConnectTimeout);
                    using (var stream = client.GetStream())
                    {
                        using (var ssl = new SslStream(stream, false, ValidateCertificate))
                        {
                            ssl.AuthenticateAsClient(remoteUri.Host, new X509Certificate2Collection(), SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, false);
                            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(remoteUri, new X509Certificate2(ssl.RemoteCertificate).Thumbprint);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new HalibutClientException(ex.Message, ex);
            }
        }
开发者ID:BradBarnich,项目名称:Halibut,代码行数:28,代码来源:DiscoveryClient.cs

示例4: OpenConnection

 internal static string OpenConnection()
 {
     errorMsg = string.Empty;
     _dataBuffer = string.Empty;
     int result = 0;
     int.TryParse(ConfigurationSupport.currentPort, out result);
     try
     {
         _client = new TcpClient(ConfigurationSupport.currentHost, result);
         string str = QuickRead(null);
         if (str != ConfigurationSupport.version)
         {
             errorMsg = errorMsg + "Mismatched versions." + Environment.NewLine;
             errorMsg = errorMsg + string.Format("SERVER: ({0})" + Environment.NewLine, str);
             errorMsg = errorMsg + string.Format("CLIENT: ({0})" + Environment.NewLine, ConfigurationSupport.version);
             CloseConnection();
         }
         if (_client.Connected)
         {
             StreamWriter writer = new StreamWriter(_client.GetStream());
             writer.WriteLine(string.Format("VersionInfo {{{0}}}", ConfigurationSupport.version));
             writer.Flush();
             _sslStreamReader = new SslStream(_client.GetStream(), false, new RemoteCertificateValidationCallback(CertificateValidationCallBack));
             try
             {
                 _sslStreamReader.AuthenticateAsClient(ConfigurationSupport.currentHost, null, SslProtocols.Ssl3, false);
             }
             catch (AuthenticationException exception)
             {
                 errorMsg = errorMsg + "SSL Authentication Error." + Environment.NewLine;
                 errorMsg = errorMsg + exception.ToString();
             }
             _sslStreamWriter = new StreamWriter(_sslStreamReader);
             _sslStreamWriter.AutoFlush = true;
             _sslStreamWriter.WriteLine(string.Format("ValidateUser {0} {1}", ConfigurationSupport.currentUsername, ConfigurationSupport.currentPassword));
             string str2 = QuickRead(_sslStreamReader);
             if (str2 == "UserID INVALID")
             {
                 CloseConnection();
                 errorMsg = "Invalid USERNAME and/or PASSWORD";
             }
             else
             {
                 isConnected = true;
                 ConfigurationSupport.userID = str2.Split(new char[0])[1];
             }
         }
     }
     catch (Exception ex)
     {
         isConnected = false;
         errorMsg = string.Format("Could not connect to {0}:{1}", ConfigurationSupport.currentHost, ConfigurationSupport.currentPort);
     }
     if (isConnected)
     {
         _readBuffer = new byte[0x100];
         _sslStreamReader.BeginRead(_readBuffer, 0, _readBuffer.Length, new AsyncCallback(SguildConnection.OnReceivedData), _client.GetStream());
     }
     return errorMsg;
 }
开发者ID:PingTrip,项目名称:PT-Sguil,代码行数:60,代码来源:SguildConnection.cs

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

示例6: Parse

        private void Parse()
        {
            TcpClient tcpclient = new TcpClient(); // create an instance of TcpClient
            tcpclient.Connect("pop.mail.ru", 995); // HOST NAME POP SERVER and gmail uses port number 995 for POP
            System.Net.Security.SslStream sslstream = new SslStream(tcpclient.GetStream()); // This is Secure Stream // opened the connection between client and POP Server
            sslstream.AuthenticateAsClient("pop.mail.ru"); // authenticate as client
            //bool flag = sslstream.IsAuthenticated; // check flag
            System.IO.StreamWriter sw = new StreamWriter(sslstream); // Asssigned the writer to stream
            System.IO.StreamReader reader = new StreamReader(sslstream); // Assigned reader to stream
            sw.WriteLine("USER [email protected]"); // refer POP rfc command, there very few around 6-9 command
            sw.Flush(); // sent to server
            sw.WriteLine("PASS utybfkmyjcnm321");
            sw.Flush();
            sw.WriteLine("RETR 5");
            sw.Flush();
            sw.WriteLine("Quit "); // close the connection
            sw.Flush();
            string str = string.Empty;
            string strTemp = string.Empty;

            while ((strTemp = reader.ReadLine()) != null)
            {
                if (".".Equals(strTemp))
                {
                    break;
                }
                if (strTemp.IndexOf("-ERR") != -1)
                {
                    break;
                }
                str += strTemp;
            }

            MessageBox.Show(str);
        }
开发者ID:mrVengr,项目名称:Crypto,代码行数:35,代码来源:MainWindow.xaml.cs

示例7: SslClient

 public SslClient(string ip, int port, UserCertificate certificate = null, int bufferSize = 1024) : base(ip, port)
 {
     try
     {
         _bufferSize = bufferSize;
         if (certificate != null)
         {
             _certificate = certificate;
         }
         else
         {
             _certificate = new X509Certificate2();
         }
         _stream = new SslStream(GetStream(), false, ServerCertificateValidation, UserCertificateSelection);
         _stream.AuthenticateAsClient(ip);
     }
     catch (AuthenticationException err)
     {
         ErrorOnAuthentication();
     }
     catch (SocketException)
     {
         ErrorOnAuthentication();
     }
     catch (Win32Exception)
     {
         ErrorOnAuthentication();
     }
 }
开发者ID:vitroums,项目名称:inzynierka,代码行数:29,代码来源:SslClient.cs

示例8: initialize

        public int initialize(IceInternal.Buffer readBuffer, IceInternal.Buffer writeBuffer, ref bool hasMoreData)
        {
            int status = _stream.connect(readBuffer, writeBuffer, ref hasMoreData);
            if(status != IceInternal.SocketOperation.None)
            {
                return status;
            }

            _stream.setBlock(true); // SSL requires a blocking socket

            if(_sslStream == null)
            {
                NetworkStream ns = new NetworkStream(_stream.fd(), false);
                _sslStream = new SslStream(ns, false, new RemoteCertificateValidationCallback(validationCallback),
                                                      new LocalCertificateSelectionCallback(selectCertificate));
                return IceInternal.SocketOperation.Connect;
            }

            Debug.Assert(_sslStream.IsAuthenticated);
            _authenticated = true;
            _instance.verifyPeer((NativeConnectionInfo)getInfo(), _stream.fd(), _host);

            if(_instance.securityTraceLevel() >= 1)
            {
                _instance.traceStream(_sslStream, _stream.ToString());
            }
            return IceInternal.SocketOperation.None;
        }
开发者ID:joshmoore,项目名称:ice,代码行数:28,代码来源:TransceiverI.cs

示例9: DaneStream

		/// <summary>
		///   Creates a new instance of the TlsaStream class
		/// </summary>
		/// <param name="innerStream">The underlying stream on which the encrypted stream should work</param>
		/// <param name="resolver">A DNSSEC resolver to get the TLSA records</param>
		/// <param name="enforceTlsaValidation">If true, the use of TLSA records is enforced</param>
		/// <param name="leaveInnerStreamOpen">If true, the underlying stream will not be closed when this instance is closed</param>
		/// <param name="userCertificateSelectionCallback">
		///   A callback to select client certificates to authenticate the client to
		///   the server
		/// </param>
		public DaneStream(Stream innerStream, IDnsSecResolver resolver, bool enforceTlsaValidation = false, bool leaveInnerStreamOpen = false, LocalCertificateSelectionCallback userCertificateSelectionCallback = null)
			: base(innerStream, leaveInnerStreamOpen)
		{
			_resolver = resolver;
			_enforceTlsaValidation = enforceTlsaValidation;
			_sslStream = new SslStream(innerStream, leaveInnerStreamOpen, ValidateRemoteCertificate, userCertificateSelectionCallback);
		}
开发者ID:huoxudong125,项目名称:ARSoft.Tools.Net,代码行数:18,代码来源:DaneStream.cs

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

示例11: Handle

        public static void Handle(ulong clientId, Packet packet, SslStream stream)
        {
            TdfEncoder encoder = new TdfEncoder();

            //TdfMap smap = new TdfMap("SMAP", TdfBaseType.TDF_TYPE_STRING, TdfBaseType.TDF_TYPE_STRING);
            //smap.Map("cust", ""); // TODO: fetch from userSettingsSave 0x000B

            encoder.WriteTdf(new List<Tdf>
            {

            });

            byte[] payload = encoder.Encode();

            Utilities.SendPacket(new Packet
            {
                componentId = Component.UTIL,
                commandId = 0xB,
                errorCode = 0,
                msgType = MessageType.REPLY,
                msgNum = packet.msgNum,

                payload = payload,
                payloadSize = payload.Length
            }, stream);
        }
开发者ID:pedromartins1,项目名称:BlazeServer,代码行数:26,代码来源:UserSettingsSaveCommand.cs

示例12: ServerClient

 public ServerClient(TcpClient client, Serverapplication server, SslStream stream)
 {
     this.server = server;
     this.client = client;
     this.stream = stream;
     if (client != null)
     {
         new Thread(() =>
         {
             BinaryFormatter formatter = new BinaryFormatter();
             while (client.Connected)
             {
                 Packet packet = NetworkFlow.ReadPacket(stream);
                 if (packet != null)
                 {
                     Console.WriteLine("recieved packet");
                     packet.handleServerSide(this);
                 }
             }
             server.getConnectedClients().Remove(this);
             if (user != null)
                 user.isOnline = false;
             Console.WriteLine("Client disconnected");
         }).Start();
     }
 }
开发者ID:rene1997,项目名称:ip2,代码行数:26,代码来源:ServerClient.cs

示例13: Connect

        public void Connect()
        {
            this.tcpClient = new TcpClient(this.host, this.port);
            this.sslStream = new SslStream(
                this.tcpClient.GetStream(),
                false,
                ValidateServerCertificate,
                null);
            var certificatesCollection = new X509Certificate2Collection(this.certificate);
            try
            {
                this.sslStream.AuthenticateAsClient(this.host, certificatesCollection, SslProtocols.Tls, false);

            }
            catch (AuthenticationException ex)
            {
                throw new NotificationException("Failed to authenticate", ex);

            }

            if (!this.sslStream.IsMutuallyAuthenticated)
            {
                throw new NotificationException("Failed to authenticate");
            }
        }
开发者ID:smoak,项目名称:libAPNs,代码行数:25,代码来源:APNSConnection.cs

示例14: Connect

    public void Connect(String server, int port, bool ssl)
    {
      String m_response = "";
      m_use_ssl = ssl;
      m_client.Connect(server, port);

      m_network_stream = m_client.GetStream();

      if (m_use_ssl)
      {
        m_ssl_stream = new SslStream((Stream)m_network_stream, true);
        m_ssl_stream.AuthenticateAsClient(server);

        m_stream = (Stream)m_ssl_stream;
      }
      else
      {
        m_stream = m_network_stream;
      }

      m_response = this.Response();

      if (m_response.Substring(0, 3) != "+OK")
      {
        throw new Pop3Exception(m_response);
      }
    }
开发者ID:balmeidaarruda,项目名称:System.Net.Pop3,代码行数:27,代码来源:Pop3Client.cs

示例15: SecureConnection

 public SecureConnection(TcpClient client, SslStream stream, MessageExchangeProtocol protocol)
 {
     this.client = client;
     this.stream = stream;
     this.protocol = protocol;
     lastUsed = DateTimeOffset.UtcNow;
 }
开发者ID:OctopusDeploy,项目名称:Halibut,代码行数:7,代码来源:SecureConnection.cs


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