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


C# SslStream.Close方法代码示例

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


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

示例1: processClient

        private void processClient(TcpClient client)
        {
            X509Certificate certificate = new X509Certificate("..\\..\\..\\Certificate\\Certificate.pfx", "KTYy77216");
            // SslStream; leaveInnerStreamOpen = false;
            SslStream stream = new SslStream(client.GetStream(), false);
            try
            {
                // clientCertificateRequired = false
                // checkCertificateRevocation = true;
                stream.AuthenticateAsServer(certificate, false, SslProtocols.Tls, true);
                Console.WriteLine("Waiting for client message ...");

                // Read a message from the client
                string input = readMessage(stream);
                Console.WriteLine("Received: {0}", input);

                // Write a message to the client
                byte[] message = Encoding.UTF8.GetBytes("Hello client, this is a message from the server :)<EOF>");
                Console.WriteLine("Sending message to client ...");
                stream.Write(message);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                stream.Close();
                client.Close();
                return;
            }
            finally
            {
                stream.Close();
                client.Close();
            }
        }
开发者ID:bemk,项目名称:rhc,代码行数:34,代码来源:SslTcpServer.cs

示例2: ListenerThreadEntry

        static void ListenerThreadEntry()
        {
            try
            {
                var listener = new TcpListener(IPAddress.Any, Port);
                listener.Start();

                using (var socket = listener.AcceptSocket())
                {
                    var serverCertificate = new X509Certificate2(CertsPath + @"\test.pfx");
                    var stream = new NetworkStream(socket);
                    using (var sslStream = new SslStream(stream, false))
                    {
                        sslStream.AuthenticateAsServer(serverCertificate, false, SslProtocols.Tls, false);

                        // terminate the connection
                        sslStream.Close();
                        socket.Disconnect(false);
                        socket.Close();

                        // this code will fail
                        using (var reader = new StreamReader(sslStream))
                        {
                            var line = reader.ReadLine();
                            Console.WriteLine("> " + line);
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc);
            }
        }
开发者ID:fandrei,项目名称:TcpClientTest2,代码行数:34,代码来源:Program.cs

示例3: runClient

        private void runClient()
        {
            TcpClient client = new TcpClient(server, port);
            Console.WriteLine("Client connected ...");

            // Create ssl stream
            SslStream stream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(validateServerCertificate), null);

            stream.AuthenticateAsClient(server);

            // write message to server
            byte[] output = Encoding.UTF8.GetBytes("Message from client :D<EOF>");
            stream.Write(output);
            stream.Flush();

            // read message from server
            string input = readMessage(stream);
            Console.WriteLine("Received: {0}", input);

            // close everything
            stream.Close();
            client.Close();
            Console.WriteLine("Client closed connection ...");
            // Press any key to continue ...
            Console.ReadKey();
        }
开发者ID:bemk,项目名称:rhc,代码行数:26,代码来源:SslTcpClient.cs

示例4: OnPrepareStream

        protected override Stream OnPrepareStream(NetworkStream stream)
        {
            var sslStream = new SslStream(stream, false);

            try
            {
                sslStream.AuthenticateAsServer(_certificate, false, SslProtocols.Tls, true);
            }
            catch (AuthenticationException e)
            {
                Console.WriteLine("Exception: {0}", e.Message);
                if (e.InnerException != null)
                {
                    Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
                }
                Console.WriteLine("Authentication failed - closing the connection.");
                sslStream.Close();
                return null;
            }

            return sslStream;
        }
开发者ID:SorenHK,项目名称:sdb,代码行数:22,代码来源:SslTcpServer.cs

示例5: SendFile

        private void SendFile(UploadData credential, FileStream fstream)
        {
            TcpClient client = new TcpClient(credential.ip, credential.port);
            SslStream ssl = new SslStream(
                client.GetStream(), false,
                new RemoteCertificateValidationCallback(AuthenticationPrimitives.ValidateServerCertificate),
                null, EncryptionPolicy.RequireEncryption);

            ssl.AuthenticateAsClient(credential.ip, null, System.Security.Authentication.SslProtocols.Tls12, false);
            ssl.Write(UsefullMethods.GetBytesFromString(credential.token));
            fstream.CopyTo(ssl);
            ssl.Close();
            fstream.Close();
        }
开发者ID:mpuzz,项目名称:folderbackuper,代码行数:14,代码来源:SyncEngine.cs

示例6: connect

        private void connect()
        {
            // Create a TCP/IP client socket.
            // machineName is the host running the server application.
            TcpClient client = new TcpClient(HOST, PORT);

            log("Client connected.");
            // Create an SSL stream that will close the client's stream.
            SslStream sslStream = new SslStream(
               client.GetStream(),
               false,
               new RemoteCertificateValidationCallback(ValidateServerCertificate),
               null
               );
            try
            {
                // The server name must match the name on the server certificate.
                sslStream.AuthenticateAsClient(CN);
                log("Server authenticated");
                protocol(sslStream);
                log("protocol finished. Exit...");
            }
            catch (AuthenticationException e)
            {
                logF("Exception: {0}", e.Message);
                if (e.InnerException != null)
                {
                    logF("Inner exception: {0}", e.InnerException.Message);
                }
                logF("Authentication failed - closing the connection.");
                client.Close();
                return;
            }
            finally
            {
                sslStream.Close();
                client.Close();
            }
        }
开发者ID:botelhorui,项目名称:secure_scheduler,代码行数:39,代码来源:ClientForm.cs

示例7: ProcessClient

        static void ProcessClient(TcpClient client)
        {
            SslStream sslStream = new SslStream(
                client.GetStream(), false);
            try
            {
                sslStream.AuthenticateAsServer(serverCertificate,
                    false, SslProtocols.Tls, true);
                DisplaySecurityLevel(sslStream);
                DisplaySecurityServices(sslStream);
                DisplayCertificateInformation(sslStream);
                DisplayStreamProperties(sslStream);
                  sslStream.ReadTimeout = 5000;
                    sslStream.WriteTimeout = 5000;
                // Read a message from the client.
                byte[] message = Encoding.UTF8.GetBytes("2 process avaiable");
                sslStream.Write(message);
                bool statelock = false;
                while (true)
                {
                    string name = ReadMessage(sslStream);
                    switch (name)
                    {
                        case "unlock<EOF>":
                            System.Diagnostics.Process.Start(@"c:\logon.exe", "-u koicho -p koicho");
                            statelock = false;
                            message = Encoding.UTF8.GetBytes("success");
                            sslStream.Write(message);
                            break;
                        case "lock<EOF>":
                            System.Diagnostics.Process.Start(@"c:\windows\system32\rundll32.exe", "user32.dll,LockWorkStation");
                            statelock = true;
                            message = Encoding.UTF8.GetBytes("success");
                            sslStream.Write(message);
                            break;
                        case "getstate<EOF>":
                            if (statelock)
                            {
                                message = Encoding.UTF8.GetBytes("locked");
                                sslStream.Write(message);
                            }
                            else
                            {
                                message = Encoding.UTF8.GetBytes("unlocked");
                                sslStream.Write(message);
                            }

                            break;
                        case "ping<EOF>":
                                message = Encoding.UTF8.GetBytes("pinged");
                                sslStream.Write(message);
                                break;
                        default:
                            message = Encoding.UTF8.GetBytes("invalid command");
                            sslStream.Write(message);
                            break;
                    }
                }
            }
            catch (AuthenticationException e)
            {
                Console.WriteLine("Exception: {0}", e.Message);
                if (e.InnerException != null)
                {
                    Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
                }
                Console.WriteLine("Authentication failed - closing the connection.");
                sslStream.Close();
                client.Close();
                return;
            }
              catch (SocketException e)
            {
                Console.WriteLine("Exception: {0}", e.Message);
                if (e.InnerException != null)
                {
                    Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
                }
                Console.WriteLine("Socket failure.");
                sslStream.Close();
                client.Close();
                return;
            }
            catch (IOException e)
            {
                Console.WriteLine("Exception: {0}", e.Message);
                if (e.InnerException != null)
                {
                    Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
                }
                Console.WriteLine("Connection failure.");
                sslStream.Close();
                client.Close();
                return;
            }
            finally
            {
                sslStream.Close();
                client.Close();
            }
//.........这里部分代码省略.........
开发者ID:predator1003,项目名称:NBU-Project-TIlt2Unlock,代码行数:101,代码来源:Program.cs

示例8: _Connect

        /// <summary>
        /// Sets up a connection to APNS and initializes the thread for sending notifications
        /// </summary>
        void _Connect()
        {
            var configuration = ApnsServiceConfiguration.GetConfiguration ();
            _certificate = new X509Certificate2 (File.ReadAllBytes (configuration.Certificate), configuration.Password,
                X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
            try {
                if (!_connection.IsNullOrDefault ())
                    _connection.Close ();

            #if DEBUG
                NSLogger.Log (NSLogLevel.Info, "Connecting to APNS...");
            #endif
                _connection = new TcpClient (apnsHostName, 2195);

                if (!_sslStream.IsNullOrDefault ())
                    _sslStream.Close ();

                _sslStream = new SslStream (_connection.GetStream (), false,
                        new RemoteCertificateValidationCallback ((sender, cert, chain, sslPolicyErrors) => { return true; }),
                        new LocalCertificateSelectionCallback ((sender, targetHost, localCerts, remoteCert, acceptableIssuers) => {
                            return _certificate;
                        }));

                var certificates = new X509CertificateCollection { _certificate };
                _sslStream.AuthenticateAsClient (apnsHostName, certificates, SslProtocols.Ssl3, false);

                if (!_sslStream.IsMutuallyAuthenticated)
                    throw new ApplicationException ("SSL Stream Failed to Authenticate", null);

                if (!_sslStream.CanWrite)
                    throw new ApplicationException ("SSL Stream is not Writable", null);

            #if DEBUG
                NSLogger.Log (NSLogLevel.Info, "Connected!");
            #endif

            } catch (Exception) {
                if (_connection.Connected) {
                    _connection.Close ();
                }

                if (!_sslStream.IsNullOrDefault ()) {
                    _sslStream.Close ();
                    _sslStream.Dispose ();
                }
                throw;
            }
        }
开发者ID:Donelle,项目名称:HowToAPNS,代码行数:51,代码来源:ApnsService.cs

示例9: CreateClientSslStream

        public static Stream CreateClientSslStream(ConnectionBase connection,
                                               Stream baseStream,
                                               X509Certificate2Collection clientCertificates,
                                               RemoteCertificateValidationCallback serverCertificateValidationCallback,
                                               LocalCertificateSelectionCallback clientCertificateSelectionCallback)
        {
            var sslStream = new SslStream(baseStream,
                                    false,
                                    serverCertificateValidationCallback,
                                    clientCertificateSelectionCallback);

              try {
            sslStream.AuthenticateAsClient(connection.host,
                                       clientCertificates,
                                       SslProtocols.Default,
                                       true);

            return sslStream;
              }
              catch (AuthenticationException) {
            sslStream.Close();

            throw;
              }
        }
开发者ID:pengyancai,项目名称:cs-util,代码行数:25,代码来源:ConnectionBase.cs

示例10: SocketStream

        public virtual string SocketStream(string xmlRequestFilePath, string xmlResponseDestinationDirectory, Dictionary<string, string> config)
        {
            var url = config["onlineBatchUrl"];
            var port = int.Parse(config["onlineBatchPort"]);
            TcpClient tcpClient;
            SslStream sslStream;

            try
            {
                tcpClient = new TcpClient(url, port);
                sslStream = new SslStream(tcpClient.GetStream(), false, ValidateServerCertificate, null);
            }
            catch (SocketException e)
            {
                throw new LitleOnlineException("Error establishing a network connection", e);
            }

            try
            {
                sslStream.AuthenticateAsClient(url);
            }
            catch (AuthenticationException e)
            {
                tcpClient.Close();
                throw new LitleOnlineException("Error establishing a network connection - SSL Authencation failed", e);
            }

            if ("true".Equals(config["printxml"]))
            {
                Console.WriteLine("Using XML File: " + xmlRequestFilePath);
            }

            using (var readFileStream = new FileStream(xmlRequestFilePath, FileMode.Open))
            {
                int bytesRead;

                do
                {
                    var byteBuffer = new byte[1024 * sizeof(char)];
                    bytesRead = readFileStream.Read(byteBuffer, 0, byteBuffer.Length);

                    sslStream.Write(byteBuffer, 0, bytesRead);
                    sslStream.Flush();
                } while (bytesRead != 0);
            }

            var batchName = Path.GetFileName(xmlRequestFilePath);
            var destinationDirectory = Path.GetDirectoryName(xmlResponseDestinationDirectory);
            if (destinationDirectory != null && !Directory.Exists(destinationDirectory)) Directory.CreateDirectory(destinationDirectory);

            if ("true".Equals(config["printxml"]))
            {
                Console.WriteLine("Writing to XML File: " + xmlResponseDestinationDirectory + batchName);
            }

            using (var writeFileStream = new FileStream(xmlResponseDestinationDirectory + batchName, FileMode.Create))
            {
                int bytesRead;

                do
                {
                    var byteBuffer = new byte[1024 * sizeof(char)];
                    bytesRead = sslStream.Read(byteBuffer, 0, byteBuffer.Length);

                    writeFileStream.Write(byteBuffer, 0, bytesRead);
                } while (bytesRead > 0);
            }

            tcpClient.Close();
            sslStream.Close();

            return xmlResponseDestinationDirectory + batchName;
        }
开发者ID:LitleCo,项目名称:litle-sdk-for-dotNet,代码行数:73,代码来源:Communications.cs

示例11: ProcessClient

        /////////////////////////////////////////////////////
        //                                                 //
        // ProcessClient()                                 //
        //                                                 //
        /////////////////////////////////////////////////////
        //Description:  Opens an SSL stream with the client,
        //              authenticating both the server to the
        //              client and vice-versa.  Processes
        //              commands sent in this stream.
        //
        //Returns:      false if told to quit the agent service
        //              or a failure occurs
        /////////////////////////////////////////////////////
        internal unsafe bool ProcessClient(TcpClient client)
        {
            IntPtr hMemStore = IntPtr.Zero;
            X509Store store = null;

            // A client has connected. Create the SslStream using the client's network stream.
            //note the TCP connection stream is automatically closed when this SSL stream object is disposed.
            try
            {
                CurrentSslStream = new SslStream(client.GetStream(), false, ValidateRemoteClientCertificate);
            }
            catch (Exception ex)
            {
                WriteConnectionLog("CONNECT:  Failed to create SSL stream:  " + ex.Message);
                return true;
            }

            // Authenticate the server to the client and vice-versa
            #region client/server authentication code
            try
            {
                WriteConnectionLog("CONNECT:  Authenticating client and server...");

                //------------------------------------------
                //          LOAD PFX CERT STORE
                //------------------------------------------
                //load the x509certificate2 from the PFX
                try
                {
                    //** get password via securestring **//
                    IntPtr pptr = IntPtr.Zero;
                    char[] str = EncryptedPassword.ToCharArray();
                    SecureString certPwd = null;

                    fixed (char* pChars = str)
                    {
                        certPwd = new SecureString(pChars, str.Length);
                    }

                    //decrypt our password in memory
                    pptr = Marshal.SecureStringToBSTR(certPwd);

                    //get x509 cert store from PFX file
                    hMemStore = CwCryptoHelper.GetX509StoreHandleFromPFX(PFXFileName, Marshal.PtrToStringBSTR(pptr));

                    //now use managed code to iterate over the store we just created from PFX
                    store = new X509Store(hMemStore);

                    //there should only be ONE certificate in this PFX store!
                    if (store.Certificates.Count != 1)
                    {
                        WriteConnectionLog("Error:  There are " + store.Certificates.Count.ToString() + " certificates in this store.  I don't know which one to extract, sorry.");

                        CwAgent.Win32Helper.CertCloseStore(hMemStore, 0);
                        //CwCryptoHelper.DestroyStore(store.Name,store.Prov
                        CurrentSslStream.Close();
                        return false;
                    }

                    //zero the password memory
                    Marshal.ZeroFreeBSTR(pptr);
                }
                catch (Exception ex)
                {
                    WriteConnectionLog("Could not extract certificate from PFX file:  " + ex.Message);
                    CurrentSslStream.Close();
                    return false;
                }

                //------------------------------------------
                //              AUTHENTICATE
                //------------------------------------------
                foreach(X509Certificate2 cert in store.Certificates)
                {
                    if (cert.HasPrivateKey)
                    {
                        CurrentSslStream.AuthenticateAsServer(cert, true, SslProtocols.Tls, false);
                        break;
                    }
                }
            }
            catch (AuthenticationException ex)
            {
                WriteConnectionLog("CONNECT:  Authentication error:  " + ex.Message);
                if (ex.InnerException != null)
                    WriteConnectionLog("CONNECT:  Additional error details:  " + ex.InnerException.Message);

//.........这里部分代码省略.........
开发者ID:kumaraguruv,项目名称:codeword,代码行数:101,代码来源:SslTcpServer.cs

示例12: SetupServerSocket

        public virtual bool SetupServerSocket()
#endif
        {
            try
            {
                //keep
                bool isSecured = false;
                string sslProtocol = "";

                //check packer
                if (SupportedChannelSerializationModes.HasFlag(ChannelSerializationMode.MessagePack))
                    DebugEx.Assert(MsgPack != null, "MessagePack serializer not provided");

                //create network stream
#if NETFX
                //Stream _netstream = new BufferedStream(new NetworkStream(base._sock, true));
                Stream _netstream = new NetworkStream(base._sock, true);

                //Wrap with a secure stream?
                if (Server.Certificate != null)
                {
                    var sslstream = new SslStream(_netstream, false);
                    try
                    {
                        //try authenticate
                        sslstream.AuthenticateAsServer(Server.Certificate, false, SslProtocols.Tls | SslProtocols.Tls12 | SslProtocols.Tls11, true);

                        //checks
                        if (!sslstream.IsAuthenticated)
                        {
                            DebugEx.Assert("Not authenticated");
                            throw new Exception("Not authenticated");
                        }
                        if (!sslstream.IsEncrypted)
                        {
                            DebugEx.Assert("No encryption");
                            throw new Exception("Not encryption");
                        }

                        //get info
                        isSecured = true;
                        sslProtocol = sslstream.SslProtocol.ToStringInvariant();

                        //use this stream from now on
                        _netstream = sslstream;
                    }
                    catch (Exception ex)
                    {
                        var msg = ex.Message;
                        if (ex.InnerException != null && ex.InnerException.Message != ex.Message)
                            msg += "  (inner msg=" + ex.InnerException.Message + ")";
                        DebugEx.TraceError("Certificate not accepted, " + msg);
                        try { Close("Certificate not accepted, " + msg); } catch { }
                        try { sslstream.Close(); base._sock.Dispose(); } catch { }
                        try { _netstream.Close(); _netstream.Dispose(); } catch { }
                        try { _sock.Close(); _sock.Dispose(); } catch { }
                        return false; //failed
                    }
                }
#endif

                //read clients packers
                var clientPackers = ChannelSerializationMode.Unkown;
                var clientPreferredPackers = ChannelSerializationMode.Unkown;
#if NETFX
                clientPackers = (ChannelSerializationMode)_netstream.ReadByte();
                clientPreferredPackers = (ChannelSerializationMode)_netstream.ReadByte();
#elif UNIVERSAL
                clientPackers = (ChannelSerializationMode)_sock.InputStream.AsStreamForRead().ReadByte();
                clientPreferredPackers = (ChannelSerializationMode)_sock.InputStream.AsStreamForRead().ReadByte();
#endif

                //filter packers
                clientPackers = clientPackers & SupportedChannelSerializationModes;
                clientPreferredPackers = clientPackers & clientPreferredPackers;
                var serverPreferredPackers = clientPackers & PreferredChannelSerializationModes;
                var commonPreferredPackers = clientPreferredPackers & serverPreferredPackers;

                //choose packer
                if ((_ChannelSerializationMode = _choosePacker(commonPreferredPackers)) == ChannelSerializationMode.Unkown &&
                    (_ChannelSerializationMode = _choosePacker(clientPreferredPackers)) == ChannelSerializationMode.Unkown &&
                    (_ChannelSerializationMode = _choosePacker(serverPreferredPackers)) == ChannelSerializationMode.Unkown &&
                    (_ChannelSerializationMode = _choosePacker(clientPackers)) == ChannelSerializationMode.Unkown)
                {
                    DebugEx.TraceError("Could not decide on packer.");
                    try { Close("Could not decide on packer."); } catch { }
#if NETFX
                    try { _netstream?.Close(); _netstream?.Dispose(); } catch { }
                    try { _sock?.Close(); _sock?.Dispose(); } catch { }
#elif UNIVERSAL
                    try { _sock?.Dispose(); } catch { }
#endif
                    return false; //failed
                }

                //write packer
#if NETFX
                var _nodelay = _sock.NoDelay;
                _sock.NoDelay = true; //Disable the Nagle Algorithm
                _netstream.WriteByte((byte)_ChannelSerializationMode);
//.........这里部分代码省略.........
开发者ID:yodiwo,项目名称:plegma,代码行数:101,代码来源:ServerChannel.cs

示例13: Handshake

        /// <summary>
        /// Perform SSL Handshake on a connected socket
        /// </summary>
        /// <param name="clientSocket">Socket object returned by Connect()</param>
        /// <returns>Stream which may be used for secure communication</returns>
        /// <remarks>Ceritifacte validation depends on RemoteCertificateValidationCallback() method</remarks>
        protected SslStream Handshake(Socket clientSocket)
        {
            NetworkStream clientSocketStream = null;
            SslStream clientSslStream = null;

            try
            {
                clientSocketStream = new NetworkStream(clientSocket); // this stream is going to be controlled by SslStream
                clientSslStream = new SslStream(clientSocketStream, false, this.RemoteCertificateValidationCallback);

                clientSslStream.AuthenticateAsClient(CertificateCommonName);

                // SslStream is necessary to read/write data
                return clientSslStream;
            }
            catch (Exception e)
            {
                if (clientSocketStream != null)
                {
                    clientSocketStream.Close();
                }
                if (clientSslStream != null)
                {
                    clientSslStream.Close();
                }
                clientSocket.Close();

                throw new Exception("Could not perform handshake process.", e);
            }
        }
开发者ID:islander98,项目名称:WinRVClient,代码行数:36,代码来源:RVClient.cs

示例14: Main

        public static void Main(string[] args)
        {
            // http://stackoverflow.com/questions/9726802/ssl-socket-between-net-and-java-with-client-authentication
            // http://stackoverflow.com/questions/27203741/java-equivalent-to-net-sslstream

            // X:\jsc.svn\core\ScriptCoreLib.Ultra.Library\ScriptCoreLib.Ultra.Library\Extensions\TcpListenerExtensions.css
            // X:\jsc.svn\examples\javascript\Test\TestTCPMultiplex\TestTCPMultiplex\Application.cs

            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201410/20141018-ssl
            // http://msdn.microsoft.com/en-us/library/ms733813.aspx
            // http://stackoverflow.com/questions/4095297/self-signed-certificates-performance-in-wcf-scenarios
            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201510/20151009

            var CN = "device SSL authority for developers";


            #region CertificateRootFromCurrentUser
            Func<X509Certificate> CertificateRootFromCurrentUser =
                delegate
            {
                X509Store store = new X509Store(
                            StoreName.Root,
                    StoreLocation.CurrentUser);
                // https://syfuhs.net/2011/05/12/making-the-x509store-more-friendly/
                // http://ftp.icpdas.com/pub/beta_version/VHM/wince600/at91sam9g45m10ek_armv4i/cesysgen/sdk/inc/wintrust.h

                // Policy Information:
                //URL = http://127.0.0.5:10500

                try
                {

                    store.Open(OpenFlags.ReadOnly);

                    var item = store.Certificates.Find(X509FindType.FindBySubjectName, CN, true);

                    if (item.Count > 0)
                        return item[0];

                }
                finally
                {

                    store.Close();
                }

                return null;

            };
            #endregion

            // Error: There is no matching certificate in the issuer's Root cert store

            var r = CertificateRootFromCurrentUser();

            if (r == null)
            {
                Process.Start(
                                          new ProcessStartInfo(
                                          @"C:\Program Files (x86)\Windows Kits\8.0\bin\x64\makecert.exe",

                           // this cert is constant
                           "-r -cy authority -a SHA1 -n \"CN=" + CN + "\"  -len 2048 -m 72 -ss Root -sr currentuser"
                                          )

                {
                    UseShellExecute = false

                }

                ).WaitForExit();
            }

            // X:\jsc.svn\examples\java\hybrid\JVMCLRSSLTCPListener\JVMCLRSSLTCPListener\Program.cs
            // https://www.npmjs.org/package/port-mux
            // http://c-skills.blogspot.com/
            // http://httpd.apache.org/docs/trunk/ssl/ssl_faq.html


            //// match HTTP GET requests (using a prefix string match) and forward them to localhost:80
            //.addRule('GET ', 80)

            //// match TLS (HTTPS) requests (versions 3.{0,1,2,3}) using a regular expression
            //.addRule(/^\x16\x03[\x00 -\x03] /, '192.168.1.1:443') // regex match

            // f you wanted to be really clever, you could use a connection proxy thing to sniff the first couple of bytes of the incoming data stream, and hand off the connection based on the contents of byte 0: if it's 0x16 (the SSL/TLS 'handshake' byte), pass the connection to the SSL side, if it's an alphabetical character, do normal HTTP. My comment about port numbering applies.
            // http://serverfault.com/questions/47876/handling-http-and-https-requests-using-a-single-port-with-nginx
            // http://www.pond-weed.com/multiplex/


            //  http://stackoverflow.com/questions/463657/makecert-is-it-possible-to-change-the-key-size

            // The certificate has to be generated with "client authentication" option
            // http://stackoverflow.com/questions/18942848/authenticate-user-via-client-signed-ssl-certificate-in-asp-net-application
            // https://github.com/mono/mono/blob/master/mcs/tools/security/makecert.cs

            //X509CertificateBuilder
            // jsc can you build a cert anywhere?

            var port = new Random().Next(8000, 12000);
//.........这里部分代码省略.........
开发者ID:exaphaser,项目名称:JSC-Cross-Compiler,代码行数:101,代码来源:Program.cs

示例15: Inspect

        public void Inspect(int mSecTimout)
        {
            this.ProtocolUsed = SslProtocols.None;
            this.ConnectivityWorks = false;
            this.CertificateErrors = new List<SSLCertError>();
            this.SpeaksSSL = false;

            TcpClient client = null;
            try {

                client = TimeOutSocket.Connect(host, port, mSecTimout);
            } catch(Exception) {

                return;
            }
            this.ConnectivityWorks = client.Connected ;

            if (!this.ConnectivityWorks)
            {
                return;
            }

            RemoteCertificateValidationCallback callback = new RemoteCertificateValidationCallback(OnCertificateValidation);
            SslStream stream = new SslStream(client.GetStream(), false, callback);
            X509CertificateCollection dummy = new X509CertificateCollection();
            try{

                    stream.AuthenticateAsClient(host,dummy, SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls | SslProtocols.Ssl3, false); //blocks
                    System.Threading.Thread.Sleep(100); //wait for good measure
            }
            catch (System.Net.Sockets.SocketException)
            {
                this.ConnectivityWorks = false;
                return;
            }
            catch (Exception)
            {
                //connection open, but not valid SSL
                this.ConnectivityWorks = true;
                return;
            }

            SpeaksSSL = true;
            this.ProtocolUsed = stream.SslProtocol;
            stream.Close();

            lock(locker) {
                try
                {
                    //there are weird conditions where the OnVertificate validation event has not fired yet, so we could get the errors collection modified
                    //if we are not careful. Wrap it to be safe
                    foreach (SSLCertError e in this.working)
                    {
                        this.CertificateErrors.Add(e);
                    }
                }
                catch (Exception)
                {

                }
            }
        }
开发者ID:zoompf,项目名称:SPDYCheck,代码行数:62,代码来源:SSLInspector.cs


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