简单c# SSL服务器:无法识别提供给包的凭据

本文关键字:识别 SSL 服务器 简单 | 更新日期: 2023-09-27 18:06:53

我很难理解为什么我简单的c# SSL服务器代码失败了。当我尝试使用从文件系统加载的.p12文件"身份验证为服务器"时,我得到一个错误。

下面是我的代码:

IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 2045);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Bind(localEndPoint);
while (true)
{
server.Listen(10);
Socket client = server.Accept();
Stream clientStream = new NetworkStream(client, true);
var clientTlsStream = new SslStream(clientStream, false);
var p12Cert =
    new X509Certificate2(
        @"C:'Repos'ITEL-Trunk'Code'Applications'Server'bin'Debug'Configuration'Certificate_tool_signed_with_ca.p12",
        "Passw0rd");
clientTlsStream.AuthenticateAsServer(p12Cert);
var cr = clientTlsStream.CanRead;

}

下面是异常细节:

System.ComponentModel.Win32Exception was unhandled
  HResult=-2147467259
  Message=The credentials supplied to the package were not recognized
  Source=System
  ErrorCode=-2147467259
  NativeErrorCode=-2146893043

X509Certificate2对象表明"拥有私钥= true",我已经尝试以管理员身份运行而没有运气。我看到的其他SO问题都是围绕CAPI权限的,但由于我直接从文件系统加载,因此无法应用这些答案。

简单c# SSL服务器:无法识别提供给包的凭据

我能够将这个问题追溯到生成p12文件的方式。.p12是由一个基于Bouncy-Castle的c#实用程序创建的,它没有正确地打包证书和私钥。我必须更改证书生成器,以便它正确地打包证书和用于签名的CA证书。

在我对证书生成器进行更改之后,"提供给包的凭据未被识别"异常消失了。

下面是似乎可以工作的P12打包程序代码:

// Create the PKCS12 store
Pkcs12Store store = new Pkcs12Store();
// Add a Certificate entry
string certCn = cert.SubjectDN.GetValues(X509Name.CN).OfType<string>().Single();
X509CertificateEntry certEntry = new X509CertificateEntry(cert);
store.SetCertificateEntry(certCn, certEntry); // use DN as the Alias.
// Add a key entry & cert chain (if applicable)
AsymmetricKeyEntry keyEntry = new AsymmetricKeyEntry(kp.Private);
X509CertificateEntry[] certChain;
if (_issuerCert != null)
{
    X509CertificateEntry issuerCertEntry = new X509CertificateEntry(_issuerCert);
    certChain = new X509CertificateEntry[] { certEntry, issuerCertEntry};
}
else
{
    certChain = new X509CertificateEntry[] { certEntry };
}
store.SetKeyEntry(certCn, keyEntry, certChain); // Set the friendly name along with the generated certs key and its chain
// Write the p12 file to disk
FileInfo p12File = new FileInfo(pathToP12File);
Directory.CreateDirectory(p12File.DirectoryName);
using (FileStream filestream = new FileStream(pathToP12File, FileMode.Create, FileAccess.ReadWrite))
{
     store.Save(filestream, password.ToCharArray(), new SecureRandom());
}