验证SSL证书

时间:2018-10-25 09:41:02

标签: c# ssl tcp tcpclient

我正在尝试通过tls / ssl将c#客户端连接到node.js服务器。服务器正在运行,我已经创建了证书。但是,如果我想通过TcpClient连接到服务器,则说证书无效。您可以自己验证该证书吗?你们有什么主意吗?

namespace Client
{
    class Program
    {
        private static TcpClient _TcpClient = new TcpClient("localhost", 8000);
        private static SslStream stream;
        static void Main(string[] args)
        {
            stream = new SslStream(_TcpClient.GetStream());
            stream.AuthenticateAsClient("localhost");

            byte[] buffer = new byte[2048];

            StringBuilder data = new StringBuilder();
            int bytes = -1;
            do
            {
                bytes = stream.Read(buffer, 0, buffer.Length);
                Decoder decoder = Encoding.UTF8.GetDecoder();
                char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
                decoder.GetChars(buffer, 0, bytes, chars, 0);
                data.Append(chars);
                if (data.ToString().IndexOf("<EOF>") != -1)
                {
                    break;
                }

            }
            while (bytes != 0);
            Console.WriteLine(data.ToString());
            Console.ReadKey();
        }

    }
}

证书是自签名的,因此我必须与客户一起发送,但是我不知道如何。即使我通过ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; 禁用了验证,它也不起作用(我只是将其放在main方法的第一行中)。

1 个答案:

答案 0 :(得分:0)

因此,我只是没有更改代码,而是按照以下指南在服务器上安装了证书:https://technet.microsoft.com/en-us/library/ff730672.aspx