【问题标题】:Simple C# SSL Server: The credentials supplied to the package were not recognized简单 C# SSL 服务器:无法识别提供给包的凭据
【发布时间】:2014-07-27 02:14:48
【问题描述】:

我很难理解为什么我的简单 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# sockets ssl x509certificate


    【解决方案1】:

    我能够将此问题追溯到生成 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());
    }
    

    【讨论】:

      猜你喜欢
      • 2015-09-09
      • 1970-01-01
      • 1970-01-01
      • 2021-05-31
      • 2011-01-20
      • 1970-01-01
      • 2015-05-03
      • 2022-06-13
      • 1970-01-01
      相关资源
      最近更新 更多