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


C# SslStream.BeginAuthenticateAsServer方法代码示例

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


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

示例1: assign_without_subscribing_on_MessageReceived_means_that_messages_can_get_lost

        public void assign_without_subscribing_on_MessageReceived_means_that_messages_can_get_lost()
        {
            var slice = new BufferSlice(new byte[65535], 0, 65535);
            var encoder = Substitute.For<IMessageEncoder>();
            var decoder = Substitute.For<IMessageDecoder>();
            var stream = new SslStream(new NetworkStream(_helper.Server));
            stream.BeginAuthenticateAsServer(_certificate, OnAuthenticated, stream);

            var sut = CreateClientChannel(slice, encoder, decoder);
            Action actual = () => sut.Assign(_helper.Client);

            actual.ShouldThrow<InvalidOperationException>();
        }
开发者ID:GitItInTheHub,项目名称:Griffin.Framework,代码行数:13,代码来源:SecureTcpChannelTests.cs

示例2: Assign_should_work_after_subscription

        public void Assign_should_work_after_subscription()
        {
            var slice = new BufferSlice(new byte[65535], 0, 65535);
            var encoder = Substitute.For<IMessageEncoder>();
            var decoder = Substitute.For<IMessageDecoder>();
            object expected;
            var stream = new SslStream(new NetworkStream(_helper.Server));
            stream.BeginAuthenticateAsServer(_certificate, OnAuthenticated, stream);

            var sut = CreateClientChannel(slice, encoder, decoder);
            sut.MessageReceived += (channel, message) => expected = message;
            sut.Assign(_helper.Client);

        }
开发者ID:GitItInTheHub,项目名称:Griffin.Framework,代码行数:14,代码来源:SecureTcpChannelTests.cs

示例3: Authenticate

        public Task Authenticate(X509Certificate2 certificate, SslProtocols enabledSslProtocols, Action callback, Action<Exception> error)
        {
            var ssl = new SslStream(_stream, false);
            _stream = new QueuedStream(ssl);
            Func<AsyncCallback, object, IAsyncResult> begin =
                (cb, s) => ssl.BeginAuthenticateAsServer(certificate, false, enabledSslProtocols, false, cb, s);
                
            Task task = Task.Factory.FromAsync(begin, ssl.EndAuthenticateAsServer, null);
            task.ContinueWith(t => callback(), TaskContinuationOptions.NotOnFaulted)
                .ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
            task.ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted);

            return task;
        }
开发者ID:SkightTeam,项目名称:Fleck,代码行数:14,代码来源:SocketWrapper.cs

示例4: should_listen_on_the_decoder_event

        public void should_listen_on_the_decoder_event()
        {
            var slice = new BufferSlice(new byte[65535], 0, 65535);
            var encoder = Substitute.For<IMessageEncoder>();
            var decoder = new FakeDecoder();
            object expected = null;
            var stream = new SslStream(new NetworkStream(_helper.Server));
            stream.BeginAuthenticateAsServer(_certificate, OnAuthenticated, stream);

            var sut = CreateClientChannel(slice, encoder, decoder);
            sut.MessageReceived += (channel, message) => expected = message;
            decoder.MessageReceived("Hello");

            expected.Should().Be("Hello");
        }
开发者ID:GitItInTheHub,项目名称:Griffin.Framework,代码行数:15,代码来源:SecureTcpChannelTests.cs

示例5: New

 public void New(TcpClient c, bool isOutBound)
 {
     var stream = new SslStream(c.GetStream());
     var remote = ((IPEndPoint)c.Client.RemoteEndPoint).Address.ToString();
     var certs = new X509CertificateCollection();
     var state = new State { Client = c, Stream = stream };
     if (isOutBound)
     {
         certs.Add(clientCertificate);
         stream.BeginAuthenticateAsClient(remote, certs, SslProtocols.Tls, false, EndAuthenticateAsClient, state);
     }
     else
     {
         certs.Add(serverCertificate);
         stream.BeginAuthenticateAsServer(serverCertificate, true, SslProtocols.Tls, false, EndAuthenticateAsServer, state);
     }
 }
开发者ID:stangelandcl,项目名称:Actors,代码行数:17,代码来源:SslByteConnectionFactory.cs

示例6: Client

        internal Client(BaseServer server, TcpClient client, X509Certificate certificate)
            : base(server)
        {
            this.client = client;
            Nstream = client.GetStream();

            cert = certificate;

            Sstream = new SslStream(Nstream, false);

            try
            {
                Sstream.BeginAuthenticateAsServer(certificate, false, SslProtocols.Default, true, FinishServerAuthentication, null);
            }
            catch (Exception x)
            {
                OnAuthFailed(new ClientAuthFailedEventArgs(x));

                _CheckIfStopped(x, true);
            }
        }
开发者ID:vercas,项目名称:vProto,代码行数:21,代码来源:Client.cs

示例7: InitServerSocket

        private void InitServerSocket(Socket socket, X509Certificate certificate, bool verbose)
        {
            Ensure.NotNull(certificate, "certificate");

            InitConnectionBase(socket);
            if (verbose) Console.WriteLine("TcpConnectionSsl::InitClientSocket({0}, L{1})", RemoteEndPoint, LocalEndPoint);

            using (_streamLock.Acquire())
            {
                try
                {
                    socket.NoDelay = true;
                }
                catch (ObjectDisposedException)
                {
                    CloseInternal(SocketError.Shutdown, "Socket is disposed.");
                    return;
                }

                _sslStream = new SslStream(new NetworkStream(socket, true), false);
                try
                {
                    _sslStream.BeginAuthenticateAsServer(certificate, false, SslProtocols.Default, true, OnEndAuthenticateAsServer, _sslStream);
                }
                catch (AuthenticationException exc)
                {
                    Log.InfoException(exc, "[S{0}, L{1}]: Authentication exception on BeginAuthenticateAsServer.", RemoteEndPoint, LocalEndPoint);
                    CloseInternal(SocketError.SocketError, exc.Message);
                }
                catch (ObjectDisposedException)
                {
                    CloseInternal(SocketError.SocketError, "SslStream disposed.");
                }
                catch (Exception exc)
                {
                    Log.InfoException(exc, "[S{0}, L{1}]: Exception on BeginAuthenticateAsServer.", RemoteEndPoint, LocalEndPoint);
                    CloseInternal(SocketError.SocketError, exc.Message);
                }
            }
        }
开发者ID:adbrowne,项目名称:EventStore,代码行数:40,代码来源:TcpConnectionSsl.cs

示例8: InitializeCryptService


//.........这里部分代码省略.........
                  SymmetricAlgorithm sa = CryptUtils.CreateSymmetricAlgoritm(connection.EncryptType);
                  sa.GenerateIV();
                  sa.GenerateKey();

                  //----- Adjust connection cryptors!
                  connection.Encryptor = sa.CreateEncryptor();
                  connection.Decryptor = sa.CreateDecryptor();

                  //----- Create authenticate structure!
                  AuthMessage am = new AuthMessage();
                  am.SessionIV = serverPublicKey.Encrypt(sa.IV, false);
                  am.SessionKey = serverPublicKey.Encrypt(sa.Key, false);
                  am.SourceKey = CryptUtils.EncryptDataForAuthenticate(sa, Encoding.UTF8.GetBytes(clientPrivateKey.ToXmlString(false)), PaddingMode.ISO10126);

                  //----- Sign message with am.SourceKey, am.SessionKey and signMessage!
                  //----- Need to use PaddingMode.PKCS7 in sign!
                  MemoryStream m = new MemoryStream();
                  m.Write(am.SourceKey, 0, am.SourceKey.Length);
                  m.Write(am.SessionKey, 0, am.SessionKey.Length);
                  m.Write(signMessage, 0, signMessage.Length);
                  
                  am.Sign = clientPrivateKey.SignData(CryptUtils.EncryptDataForAuthenticate(sa, m.ToArray(), PaddingMode.PKCS7), new SHA1CryptoServiceProvider());

                  //----- Serialize authentication message!
                  XmlSerializer xml = new XmlSerializer(typeof(AuthMessage));
                  m.SetLength(0);
                  xml.Serialize(m, am);

                  //----- Send structure!
                  MessageBuffer mb = new MessageBuffer(0);
                  mb.PacketBuffer = Encoding.GetEncoding(1252).GetBytes(Convert.ToBase64String(m.ToArray()));
                  connection.Socket.BeginSend(mb.PacketBuffer, mb.PacketOffSet, mb.PacketRemaining, SocketFlags.None, new AsyncCallback(InitializeConnectionSendCallback), new CallbackData(connection, mb));

                  m.Close();
                  am.SessionIV.Initialize();
                  am.SessionKey.Initialize();
                  serverPublicKey.Clear();
                  clientPrivateKey.Clear();

              }
              else
              {

                  //----- Create empty authenticate structure!
                  MessageBuffer mb = new MessageBuffer(8192);

                  //----- Start receive structure!
                  connection.Socket.BeginReceive(mb.PacketBuffer, mb.PacketOffSet, mb.PacketRemaining, SocketFlags.None, new AsyncCallback(InitializeConnectionReceiveCallback), new CallbackData(connection, mb));

              }

          }

          //----- Asymmetric!
          if (connection.EncryptType == EncryptType.etSSL)
          {

              if (FHost.HostType == HostType.htClient)
              {

                  //----- Get SSL items!
                  X509Certificate2Collection certs = null;
                  string serverName = null;
                  bool checkRevocation = true;

                  FCryptoService.OnSSLClientAuthenticate(connection, out serverName, ref certs, ref checkRevocation);

                  //----- Authneticate SSL!
                  SslStream ssl = new SslStream(new NetworkStream(connection.Socket), true, new RemoteCertificateValidationCallback(ValidateServerCertificateCallback)); 

                  if (certs == null)
                  {
                      ssl.BeginAuthenticateAsClient(serverName, new AsyncCallback(SslAuthenticateCallback), new AuthenticateCallbackData(connection, ssl, HostType.htClient));
                  }
                  else
                  {
                      ssl.BeginAuthenticateAsClient(serverName, certs, System.Security.Authentication.SslProtocols.Default, checkRevocation, new AsyncCallback(SslAuthenticateCallback), new AuthenticateCallbackData(connection, ssl, HostType.htClient));

                  }

              }
              else
              {

                  //----- Get SSL items!
                  X509Certificate2 cert = null;
                  bool clientAuthenticate = false;
                  bool checkRevocation = true;

                  FCryptoService.OnSSLServerAuthenticate(connection, out cert, out clientAuthenticate, ref checkRevocation);

                  //----- Authneticate SSL!
                  SslStream ssl = new SslStream(new NetworkStream(connection.Socket));
                  ssl.BeginAuthenticateAsServer(cert, clientAuthenticate, System.Security.Authentication.SslProtocols.Default, checkRevocation, new AsyncCallback(SslAuthenticateCallback), new AuthenticateCallbackData(connection, ssl, HostType.htServer));

              }

          }

        }
开发者ID:spzenk,项目名称:sfdocsamples,代码行数:101,代码来源:BaseSocketConnectionCreator.cs

示例9: BeginAuthenticationAsServer

 public void BeginAuthenticationAsServer(X509Certificate2 certificate, SslProtocols protocols, AsyncCallback callback, object state)
 {
     SslStream sslStream = new SslStream(Stream, false);
     Stream = sslStream;
     sslStream.BeginAuthenticateAsServer(certificate, false, protocols, false, callback, state);
 }
开发者ID:IRlyDontKnow,项目名称:websocketproxy,代码行数:6,代码来源:TcpHost.cs

示例10: MaybeStartTLS

        /// <summary>
        /// Starts the TLS procedure ONLY if it's the correct time to do so.
        /// This is dependent on several variables, such as the kPause flags, connected property, etc.
        /// 
        /// This method is NOT thread safe, and should only be invoked via thread safe methods.
        /// </summary>
        private void MaybeStartTLS()
        {
            Debug.Assert(socketStream != null, "Attempting to start tls without a connected socket");
            Trace.Assert(secureSocketStream == null, "Attempting to start tls after tls has already completed");

            // We can't start TLS until:
            // - Any queued reads prior to the user calling StartTLS are complete
            // - Any queued writes prior to the user calling StartTLS are complete

            if (((flags & kPauseReads) > 0) && ((flags & kPauseWrites) > 0))
            {
                try
                {
                    secureSocketStream = new SslStream(socketStream, true, tlsRemoteCallback, tlsLocalCallback);

                    if (isTLSClient)
                    {
                        secureSocketStream.BeginAuthenticateAsClient(tlsServerName,
                                                   new AsyncCallback(secureSocketStream_DidFinish), null);
                    }
                    else
                    {
                        secureSocketStream.BeginAuthenticateAsServer(localCertificate,
                                                   new AsyncCallback(secureSocketStream_DidFinish), null);
                    }
                }
                catch (Exception e)
                {
                    // The most likely cause of this exception is a null tlsServerName.
                    CloseWithException(e);
                }
            }
        }
开发者ID:Gemini2015,项目名称:dotnetasyncsocket,代码行数:39,代码来源:AsyncSocket.cs

示例11: send_message

        public void send_message()
        {
            var slice = new BufferSlice(new byte[65535], 0, 65535);
            var encoder = new StringEncoder();
            var decoder = new StringDecoder();
            object expected = null;

            var sut = CreateClientChannel(slice, encoder, decoder);
            sut.MessageReceived += (channel, message) => expected = message;
            var stream = new SslStream(new NetworkStream(_helper.Server));
            stream.BeginAuthenticateAsServer(_certificate, OnAuthenticated, stream);
            sut.Assign(_helper.Client);
            sut.Send("Hello world");

            var buf = new byte[65535];
            var tmp = stream.Read(buf, 0, 65535);
            var actual = Encoding.ASCII.GetString(buf, 4, tmp-4); // string encoder have a length header.
            actual.Should().Be("Hello world");
        }
开发者ID:jorgenlidholm,项目名称:Griffin.Framework,代码行数:19,代码来源:SecureTcpChannelTests.cs

示例12: connectionHandler

            public connectionHandler(Socket socket, HttpServer server, bool secure)
            {
                Socket = socket;

                _requestId = Rnd.Next();
                _requestStart = DateTime.UtcNow;
                _server = server;
                _secure = secure;

                _server.Log.Info(4, "{0:X8} Incoming connection from {1}".Fmt(_requestId, socket.RemoteEndPoint));

                _buffer = new byte[1024];
                _bufferDataOffset = 0;
                _bufferDataLength = 0;

                _headersSoFar = "";

                lock (server._activeConnectionHandlers)
                    server._activeConnectionHandlers.Add(this);

                var stream = new NetworkStream(socket, ownsSocket: true);
                if (_secure)
                {
                    var secureStream = new SslStream(stream);
                    _stream = secureStream;
                    secureStream.BeginAuthenticateAsServer(new X509Certificate2(server.Options.CertificatePath, server.Options.CertificatePassword), false, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, true, ar =>
                    {
                        try
                        {
                            secureStream.EndAuthenticateAsServer(ar);
                        }
                        catch (Exception e)
                        {
                            Socket.Close();
                            cleanupIfDone();
                            if (_server.ResponseExceptionHandler != null)
                                _server.ResponseExceptionHandler(null, e, null);
                            return;
                        }
                        receiveMoreHeaderData();
                    }, null);
                }
                else
                {
                    _stream = stream;
                    receiveMoreHeaderData();
                }
            }
开发者ID:RT-Projects,项目名称:RT.Servers,代码行数:48,代码来源:HttpServer.cs

示例13: AcceptConnections

        private void AcceptConnections(string threadName)
        {
            try
            {
                Thread.CurrentThread.Name = threadName;

                logger.Debug("SIPTLSChannel socket on " + m_localSIPEndPoint + " accept connections thread started.");

                while (!Closed)
                {
                    try
                    {
                        TcpClient tcpClient = m_tlsServerListener.AcceptTcpClient();
                        tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

                        IPEndPoint remoteEndPoint = (IPEndPoint)tcpClient.Client.RemoteEndPoint;
                        logger.Debug("SIP TLS Channel connection accepted from " + remoteEndPoint + ".");

                        SslStream sslStream = new SslStream(tcpClient.GetStream(), false);

                        SIPConnection sipTLSConnection = new SIPConnection(this, sslStream, remoteEndPoint, SIPProtocolsEnum.tls, SIPConnectionsEnum.Listener);

                        sslStream.BeginAuthenticateAsServer(m_serverCertificate, EndAuthenticateAsServer, sipTLSConnection);

                        //sslStream.AuthenticateAsServer(m_serverCertificate, false, SslProtocols.Tls, false);
                        //// Display the properties and settings for the authenticated stream.
                        ////DisplaySecurityLevel(sslStream);
                        ////DisplaySecurityServices(sslStream);
                        ////DisplayCertificateInformation(sslStream);
                        ////DisplayStreamProperties(sslStream);

                        //// Set timeouts for the read and write to 5 seconds.
                        //sslStream.ReadTimeout = 5000;
                        //sslStream.WriteTimeout = 5000;

                        ////SIPConnection sipTLSConnection = new SIPConnection(this, sslStream, remoteEndPoint, SIPProtocolsEnum.tls, SIPConnectionsEnum.Listener);
                        //m_connectedSockets.Add(remoteEndPoint.ToString(), sipTLSConnection);

                        //sipTLSConnection.SIPSocketDisconnected += SIPTLSSocketDisconnected;
                        //sipTLSConnection.SIPMessageReceived += SIPTLSMessageReceived;
                        ////byte[] receiveBuffer = new byte[MaxSIPTCPMessageSize];
                        //sipTLSConnection.SIPStream.BeginRead(sipTLSConnection.SocketBuffer, 0, MaxSIPTCPMessageSize, new AsyncCallback(ReceiveCallback), sipTLSConnection);
                    }
                    catch (Exception e)
                    {
                        logger.Error("SIPTLSChannel Accept Connection Exception. " + e);
                        //sslStream.Close();
                        //tcpClient.Close();
                    }
                }

                logger.Debug("SIPTLSChannel socket on " + m_localSIPEndPoint + " listening halted.");
            }
            catch (Exception excp)
            {
                logger.Error("Exception SIPTLSChannel Listen. " + excp);
                //throw excp;
            }
        }
开发者ID:Dawn2Yuan,项目名称:sipsorcery,代码行数:59,代码来源:SIPTLSChannel.cs

示例14: ProcessConnection

        void ProcessConnection(Socket listener, IAsyncResult ar)
        {
            Socket ns = listener.EndAccept (ar);
            ns.NoDelay = true;
            SslStream ssl = new SslStream (new NetworkStream (ns, true));

            ssl.BeginAuthenticateAsServer (cert, (IAsyncResult ar2) => {
                try {
                    ssl.EndAuthenticateAsServer (ar2);
                    Protocol p = new Protocol ();
                    p.OnMessage += (incoming) => {
                        var hdr = incoming.Header;
                        // TODO timeout handling
                        if (hdr ["type"].AsString(null) != "request") {
                            Logger.LogError ("received non-request");
                            incoming.Discard ();
                            return;
                        }
                        if (!hdr.ContainsKey ("request_id")) {
                            Logger.LogError ("Received request with no request_id");
                            incoming.Discard ();
                            return;
                        }
                        var id = hdr ["request_id"];
                        reqh (incoming, (reply) => {
                            reply.Header ["type"] = "reply";
                            reply.Header ["request_id"] = id;
                            p.SendMessage (reply);
                        });
                    };
                    p.OnClose += (error) => {
                        Logger.LogInfo ("scamp connection closed: {0}", error);
                    };
                    p.Start (ssl);
                } catch (Exception ex) {
                    Logger.LogError ("connection server authenticate: {0}", ex);
                }
            }, null);
        }
开发者ID:dnorman,项目名称:scamp,代码行数:39,代码来源:SCAMPSOAServer.cs

示例15: NegotiateStream

        private Stream NegotiateStream(Stream stream)
        {
            if (!_configuration.SslEnabled)
                return stream;

            var validateRemoteCertificate = new RemoteCertificateValidationCallback(
                (object sender,
                X509Certificate certificate,
                X509Chain chain,
                SslPolicyErrors sslPolicyErrors)
                =>
                {
                    if (sslPolicyErrors == SslPolicyErrors.None)
                        return true;

                    if (_configuration.SslPolicyErrorsBypassed)
                        return true;
                    else
                        _log.ErrorFormat("Session [{0}] error occurred when validating remote certificate: [{1}], [{2}].",
                            this, this.RemoteEndPoint, sslPolicyErrors);

                    return false;
                });

            var sslStream = new SslStream(
                stream,
                false,
                validateRemoteCertificate,
                null,
                _configuration.SslEncryptionPolicy);

            var ar = sslStream.BeginAuthenticateAsServer(
                _configuration.SslServerCertificate, // The X509Certificate used to authenticate the server.
                _configuration.SslClientCertificateRequired, // A Boolean value that specifies whether the client must supply a certificate for authentication.
                _configuration.SslEnabledProtocols, // The SslProtocols value that represents the protocol used for authentication.
                _configuration.SslCheckCertificateRevocation, // A Boolean value that specifies whether the certificate revocation list is checked during authentication.
                null, _tcpClient);
            if (!ar.AsyncWaitHandle.WaitOne(ConnectTimeout))
            {
                Close();
                throw new TimeoutException(string.Format(
                    "Negotiate SSL/TSL with remote [{0}] timeout [{1}].", this.RemoteEndPoint, ConnectTimeout));
            }

            // When authentication succeeds, you must check the IsEncrypted and IsSigned properties 
            // to determine what security services are used by the SslStream. 
            // Check the IsMutuallyAuthenticated property to determine whether mutual authentication occurred.
            _log.DebugFormat(
                "Ssl Stream: SslProtocol[{0}], IsServer[{1}], IsAuthenticated[{2}], IsEncrypted[{3}], IsSigned[{4}], IsMutuallyAuthenticated[{5}], "
                + "HashAlgorithm[{6}], HashStrength[{7}], KeyExchangeAlgorithm[{8}], KeyExchangeStrength[{9}], CipherAlgorithm[{10}], CipherStrength[{11}].",
                sslStream.SslProtocol,
                sslStream.IsServer,
                sslStream.IsAuthenticated,
                sslStream.IsEncrypted,
                sslStream.IsSigned,
                sslStream.IsMutuallyAuthenticated,
                sslStream.HashAlgorithm,
                sslStream.HashStrength,
                sslStream.KeyExchangeAlgorithm,
                sslStream.KeyExchangeStrength,
                sslStream.CipherAlgorithm,
                sslStream.CipherStrength);

            return sslStream;
        }
开发者ID:xiaomiwk,项目名称:Cowboy,代码行数:65,代码来源:TcpSocketSession.cs


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