且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Npgsql 与 .net core web api 中的 ssl 证书的连接

更新时间:2023-02-15 12:38:24

我得到了一个解决方案,并想在这里发布它,这可能会帮助面临类似问题的其他人.

I got a solution for this and thought of posting it here which may help others who are facing the similar issue.

它不适用于 .pem 文件.我已使用以下命令将其转换为 .pfx 文件,并且开始正常工作.

It didn't worked with .pem files. I have converted it to a .pfx file using the below command and it started working fine.

openssl pkcs12 -inkey C:\Certs\client-key.pem -in C:\Certs\client-cert.pem -export -out C:\Certs\client-cert.pfx

参考:证书认证支持

编辑

我没有创建物理 pfx 文件,而是能够组合两个 pem 文件并使其工作.下面给出代码片段以供日后参考.

Instead of creating the physical pfx file, I was able to combine the two pem files and got it worked. Code snippet is given below for someone for reference in future.

public X509Certificate2 GetCombinedCertificateAndKey(string certificatePath, string privateKeyPath)
    {
        using var publicKey = new X509Certificate2(certificatePath);

        var privateKeyText = System.IO.File.ReadAllText(privateKeyPath);
        var privateKeyBlocks = privateKeyText.Split("-", StringSplitOptions.RemoveEmptyEntries);
        var privateKeyBytes = Convert.FromBase64String(privateKeyBlocks[1]);
        using var rsa = RSA.Create();

        if (privateKeyBlocks[0] == "BEGIN PRIVATE KEY")
        {
            rsa.ImportPkcs8PrivateKey(privateKeyBytes, out _);
        }
        else if (privateKeyBlocks[0] == "BEGIN RSA PRIVATE KEY")
        {
            rsa.ImportRSAPrivateKey(privateKeyBytes, out _);
        }

        var keyPair = publicKey.CopyWithPrivateKey(rsa);
        var Certificate = new X509Certificate2(keyPair.Export(X509ContentType.Pfx));
        return Certificate;
    }