.net core TLS 服务器证书以及 TPM 中的私钥

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

我正在尝试在 .net core 库中执行与此命令等效的操作,以执行 TLS 服务器,其中私钥位于 TPM 中,引用为 0x8100001:

openssl s_server -cert rsa.crt -key 0x8100001-keyform engine -engine tpm2tss -accept 8443

我们需要它在 .net core 上的 Ubuntu 中运行。在 Windows 中,这是由具有加密提供程序的证书存储很好地抽象的,但在 Ubuntu 中不存在同样的情况。

有人有使用在 Ubuntu 中运行的软件包的示例吗?下面是我们在 Windows 中从证书存储中获取的等效内容(证书存储抽象了 TPM 访问权限)

X509Store store = new X509Store(storeName, StoreLocation.CurrentUser);  
store.Open(OpenFlags.ReadOnly);  
X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindBySubjectName, commonName,false);  
ubuntu tls1.2 tpm
1个回答
0
投票

尝试使用 Pkcs11Interop,您首先必须在 ubuntu 上安装 tpm2-tools tpm2-pkcs11 libtss2-tcti-tabrmd0,为 TPM 配置 PKCS 令牌,然后导入密钥。

在您的 .net 项目上添加包 Pkcs11Interop 以从 TPM 访问证书和私钥:

using System;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using Net.Pkcs11Interop.HighLevelAPI;
using Net.Pkcs11Interop.HighLevelAPI.Factories;
using Net.Pkcs11Interop.Common;

public class TlsServer
{
    public static void StartServer()
    {
        // Specify the path to your PKCS#11 library
        string pkcs11LibraryPath = "/usr/lib/x86_64-linux-gnu/libtpm2_pkcs11.so";

        using (var pkcs11Library = new Pkcs11(pkcs11LibraryPath, AppType.MultiThreaded))
        {
            // Initialize the library
            var slot = pkcs11Library.GetSlotList(SlotsType.WithTokenPresent)[0];
            var session = slot.OpenSession(SessionType.ReadOnly);

            // Authenticate to the token
            session.Login(CKU.CKU_USER, "1234"); // User PIN

            // Find the private key by label
            var searchTemplate = new List<ObjectAttribute>
            {
                new ObjectAttribute(CKA.CKA_LABEL, "tls-key"),
                new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_PRIVATE_KEY)
            };
            var foundObjects = session.FindAllObjects(searchTemplate);

            if (foundObjects.Count == 0)
            {
                Console.WriteLine("Private key not found");
                return;
            }

            // Load certificate (for TLS handshake)
            var certificate = new X509Certificate2("path/to/your_cert.crt");

            // Configure the listener
            var listener = new TcpListener(IPAddress.Any, 8443);
            listener.Start();
            Console.WriteLine("Server started on port 8443");

            // Accept connections and handle with TLS
            while (true)
            {
                var client = listener.AcceptTcpClient();
                var sslStream = new SslStream(client.GetStream(), false);
                sslStream.AuthenticateAsServer(certificate, clientCertificateRequired: false, enabledSslProtocols: SslProtocols.Tls12, checkCertificateRevocation: false);
                Console.WriteLine("Client connected and authenticated");
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.