当证书位于 HSM 中且私钥未嵌入证书且私钥无法从 HSM 中提取时,如何作为服务器进行身份验证

问题描述 投票:0回答:2

我想根据我的代码问一个问题,我的代码如下: 在 AuthenticateAsServer 中,我得到 “服务器模式 SSL 必须使用具有关联私钥的证书” 错误,因为私钥不在我的证书中,而且私钥也无法从 HSM 中提取,请指导我这里的解决方案是什么?

     static void ProcessClient(TcpClient client)
    {
        SslStream sslClientStream = new SslStream(client.GetStream(), true, AllowAnyServerCertificate, null, EncryptionPolicy.RequireEncryption);

        try
        {
            X509Certificate2 _HsmserverCertificate = null;

            string pkcs11LibraryPath = "C:\\Program Files (x86)\\nCipher\\nfast\\toolkits\\pkcs11\\cknfast-64.dll";

            Pkcs11InteropFactories factories = new Pkcs11InteropFactories();

            using (IPkcs11Library pkcs11Library = factories.Pkcs11LibraryFactory.LoadPkcs11Library(factories, pkcs11LibraryPath, AppType.MultiThreaded))
            {
                ISlot slot = HelpersMethods.GetUsableSlot(pkcs11Library);

                using (Net.Pkcs11Interop.HighLevelAPI.ISession session = slot.OpenSession(SessionType.ReadWrite))
                {
                    session.Login(CKU.CKU_USER, @"1234");

                    var certificate = ReadCertificates(slot, session)[0];

                    _HsmserverCertificate = new X509Certificate2(certificate.CkaValue);
                    
                    session.Logout();
                }
            }

            sslClientStream.ReadTimeout = glb_intReciveTimeOut;
            sslClientStream.WriteTimeout = glb_intSendTimeOut;

            sslClientStream.AuthenticateAsServer(_HsmserverCertificate,
                                                 clientCertificateRequired: false,
                                                 SslProtocols.Tls12,
                                                 checkCertificateRevocation: true);
    }
}
c# tcpclient pkcs#11 pkcs11interop hardware-security-module
2个回答
1
投票

.NET 世界不成文的规则: 如果你想在 SSL 连接中使用实例

X509Certificate2
类,那么你不能手动创建它,而是需要从
X509Store
获取它。

X509Store
类提供对传播到 Windows 证书存储中的所有证书的访问。请查看您的设备文档,了解有关如何将设备证书传播到 Windows 证书存储区的更多详细信息。有时它也被称为 CAPI、CSP、CNG、KSP 等。如果您不熟悉这些术语,那么最好的办法是联系设备供应商支持。


0
投票

适用于面向 Linux 的 .NET 开发人员。

在 .NET 6 中,我成功使用 X509Certificate2(PK 存储在 TPM2.0 中)来配置 HttpClientHandler.ClientCertificates,从而在 Debian 机器上启用 MTLS。因此,我认为 SslStream 也应该 wotk。更多详细信息请参见此 GitHub 票证:https://github.com/dotnet/runtime/issues/94493 和要点 https://gist.github.com/adadurov/292818c4da0301f16f5922820da410d0

希望这能帮助未来的访客解决这个问题。

© www.soinside.com 2019 - 2024. All rights reserved.