运行x509的库做TSL加密的时候报错“调用 SSPI 失败,请参见内部异常”。

运行x509的库报错

调用.net的库运行报错如下。
" at System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, Exception exception)\r\n at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)\r\n at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)\r\n at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)\r\n at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)\r\n at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)\r\n at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)\r\n at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest, Boolean renegotiation)\r\n at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)\r\n at console.TLSServer.Main(String[] args) in C:\Users\admin\Desktop\Socket\ssl\Program.cs:line 103" 调用 SSPI 失败,请参见内部异常。

1.在使用 New-SelfSignedCertificate 命令创建自签名证书时,你可以通过 -KeyExportPolicy Exportable 参数来设置私钥可导出,然后你将能够为私钥设置密码。下面是具体步骤:

2.打开 PowerShell 作为管理员(右键单击 PowerShell,选择“以管理员身份运行”)。

3.使用以下命令创建自签名证书,并设置私钥可导出:

New-SelfSignedCertificate -DnsName “YourServerName” -CertStoreLocation “Cert:\LocalMachine\My” -KeyExportPolicy Exportable
请确保将 “YourServerName” 替换为你的服务器名称或域名。

4.命令执行成功后,它将创建一个新的自签名证书并将其存储在“个人”证书存储区域(My)中,并且私钥可导出。

5.现在,你可以为私钥设置密码。使用以下命令来为私钥设置密码:

$cert = Get-ChildItem -Path Cert:\LocalMachine\My | Where-Object { $_.Subject -eq “CN=YourServerName” }
$cert | Export-PfxCertificate -FilePath “C:\Path\To\ExportedCertificate.pfx” -Password (ConvertTo-SecureString -String “YourPassword” -Force -AsPlainText)
请将 “YourPassword” 替换为你想要设置的密码,并将输出的证书保存到指定路径。

这样,你就为自签名证书的私钥设置了密码。确保将密码保存在安全的地方,因为它将用于访问证书的私钥。在你的应用程序中,你需要提供这个密码以访问证书的私钥。



using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace console
{
    class TLSServer
    {
        /// <summary>
         /// 取整数的某一位
         /// </summary>
         /// <param name="_Resource">要取某一位的整数</param>
         /// <param name="_Mask">要取的位置索引,自右至左为0-7</param>
         /// <returns>返回某一位的值(0或者1)</returns>
        public static bool getIntegerSomeBit(int _Resource, int _Mask)
        {
            return (_Resource >> _Mask & 1)==1;
        }

        /// <summary>
        /// 将整数的某位置为0或1
        /// </summary>
        /// <param name="_Mask">整数的某位</param>
        /// <param name="a">整数</param>
        /// <param name="flag">是否置1,TURE表示置1,FALSE表示置0</param>
        /// <returns>返回修改过的值</returns>
        public static int setIntegerSomeBit(int _Mask, int a, bool flag)
        {
            if (flag)
            {
                a |= (0x1 << _Mask);
            }
            else
            {
                a &=~(0x1 << _Mask);
            }
            return a;
        }
        static void Main(string[] args)
        {
            //int value= 235;
            //value = (value >> 3);
            //int g = value & 1;
            //List<bool> listbool = new List<bool>();
            //for (int i = 0; i < 8; i++)
            //{
            //    bool nn = getIntegerSomeBit(235, i);
            //    listbool.Add(nn);
            //}
            //int ff = 1;
            //for (int i = 0; i < 8; i++)
            //{
            //     ff = setIntegerSomeBit(i, ff, true);
            //}
          
            int port = 443;
            string certificatePath = "ExportedCertificate.pfx"; // 替换成你的证书路径
            string certificatePassword = "Your-P*/assword"; // 替换成你的证书密码

            TcpListener listener = new TcpListener(IPAddress.Any, port);
            listener.Start();
            Console.WriteLine("加载证书...");

            // 加载服务器证书
            X509Certificate2 serverCertificate = new X509Certificate2(certificatePath, certificatePassword);

            while (true)
            {
                Console.WriteLine("等待连接...");
                using (TcpClient client = listener.AcceptTcpClient())
                {
                    using (SslStream sslStream = new SslStream(client.GetStream(), false))
                    {
                        try
                        {
                            // 在这里设置支持的协议版本
                            SslProtocols enabledProtocols = SslProtocols.Tls12;
                            sslStream.AuthenticateAsServer(serverCertificate, false, enabledProtocols, false);

                            Console.WriteLine("连接已建立,等待客户端发送数据...");

                            // 从客户端接收数据
                            byte[] buffer = new byte[4096];
                            int bytesRead;
                            StringBuilder data = new StringBuilder();
                            do
                            {
                                bytesRead = sslStream.Read(buffer, 0, buffer.Length);
                                string str = "";
                                for (int i = 0; i < bytesRead; i++)
                                {
                                    string str1 = buffer[i].ToString("X2");
                                    str += str1 + " ";
                                }
                                Console.WriteLine($"接收到的HEX数据:{str}");
                                Console.WriteLine($"接收到的STR数据:{Encoding.UTF8.GetString(buffer, 0, bytesRead)}");
                                data.Append(Encoding.UTF8.GetString(buffer, 0, bytesRead));

                            } while (bytesRead > 0);

                            Console.WriteLine("接收到的数据:");
                            Console.WriteLine(data.ToString());

                            // 在这里可以对接收到的数据进行处理
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("发生异常: " + ex.Message);
                        }
                    }
                }
            }
        }
    }
}


原因分析:

这个错误通常表示在 SSL/TLS 握手过程中出现了问题。它可能是由于多种原因引起的,包括证书问题、协议不匹配、密钥问题等。在处理此错误时,可以考虑以下步骤来诊断和解决问题:

证书问题:确保服务器证书正确配置,并且客户端和服务器都可以访问证书。如果证书被密码保护,请确保在应用程序中提供了正确的密码。

协议匹配:检查客户端和服务器使用的 SSL/TLS 协议版本是否匹配。你的服务器代码中使用的是 TLS 1.2,因此客户端也应该支持 TLS 1.2。确保协议版本配置正确。

密钥问题:确保服务器证书的私钥与证书匹配,并且私钥没有被破坏或更改。如果证书和私钥是分开存储的,请确保它们都正确。

异常处理:在你的代码中,你可以添加更多的异常处理来捕获和处理异常情况,以便更好地了解问题所在。你可以查看异常的详细信息,以获取更多的调试信息。

日志记录:添加详细的日志记录,以便在发生问题时能够更轻松地追踪问题。记录 SSL/TLS 握手和其他重要事件,以帮助诊断问题。

防火墙和网络问题:确保防火墙或网络设备没有阻止 SSL/TLS 流量。检查网络配置以确保连接可以建立。

更新和修复:确保你的操作系统和加密库是最新的,并且已应用所有必要的安全补丁。有时,问题可能是由于已知的漏洞引起的,可以通过更新来解决。

第三方库和框架:如果你使用了第三方库或框架来处理 SSL/TLS,确保它们是最新版本,并且正确配置。

最终,诊断和解决 SSL/TLS 握手问题可能需要深入的调试和分析。如果以上步骤无法解决问题,可能需要考虑使用专业的安全工具和服务来帮助排除问题。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值