首页 > 解决方案 > 如何从 crt 和密钥文件创建 X509Certificate2?

问题描述

我正在尝试使用私钥创建一个 X509Certificate2。要获取私钥,我正在处理此代码:

using System;
using System.Security.Cryptography;

namespace whats_new
{
    public static class RSATest
    {
        public static void Run(string keyFile)
        {
            using var rsa = RSA.Create();

            byte[] keyBytes = System.IO.File.ReadAllBytes(keyFile);
            rsa.ImportRSAPrivateKey(keyBytes, out int bytesRead);

            Console.WriteLine($"Read {bytesRead} bytes, {keyBytes.Length - bytesRead} extra byte(s) in file.");
            RSAParameters rsaParameters = rsa.ExportParameters(true);
            Console.WriteLine(BitConverter.ToString(rsaParameters.D));
        }
    }
}

我从 Microsoft 文档获得此代码:https ://docs.microsoft.com/en-us/dotnet/core/whats-new/dotnet-core-3-0#cryptographic-key-importexport

但我在这一行收到错误“ASN1 损坏的数据”:

rsa.ImportRSAPrivateKey(keyBytes, out int bytesRead);

我真正想做的是使用 crt 和密钥创建一个 X509Certificate2 证书,因为在我的 gRPC 服务中,我需要证书同时具有这两者。这是因为我使用 OpenSsl 创建了证书,我为证书生成了一个文件,为密钥生成了另一个文件。

谢谢。

标签: c#.net-corex509certificate2

解决方案


推荐阅读