使用C#中的RSA私钥文件创建RSACryptoServiceProvider对象

如何使用RSA私钥文件正确创建RSACryptoServiceProvider对象? 我生成了一个RSA私钥,并使用以下方法将其导出到OSX上的p12文件:

 openssl genrsa -out rsakey.pem 2048 openssl pkcs12 -export -out rsakey.p12 -inkey rsakey.pem -nocerts 

在我在Windows笔记本电脑上运行的C#代码中,我在尝试实例化X509Certificate2对象时遇到错误,以便我可以将私钥作为RSACryptoServiceProvider对象从中获取:

 var privateKey = new X509Certificate2(p12_file, "pass", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet).PrivateKey as RSACryptoServiceProvider; 

CryptographicException:参数不正确。

以下是整个C#代码供参考。 请注意,我只是尝试通过遵循X509Certificate2类的文档来获取私钥作为RSACryptoServiceProvider对象。

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Net; using System.Security; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Globalization; using Jose; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string p12_file = @"C:\Root\rsakey.p12"; DateTime issued = DateTime.Now; DateTime expire = DateTime.Now.AddHours(10); var payload = new Dictionary() { { "iss", "auth0_user"}, { "exp", ToUnixTime(expire).ToString() } }; var privateKey = new X509Certificate2(p12_file, "pass", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet).PrivateKey as RSACryptoServiceProvider; string token = Jose.JWT.Encode(payload, privateKey, JwsAlgorithm.RS256); Console.WriteLine(token); } static long ToUnixTime(DateTime dateTime) { return (int)(dateTime.ToUniversalTime().Subtract(new DateTime(1970, 1, 1))).TotalSeconds; } } } 

更新:我尝试使用创建自签名证书

 openssl req -key rsakey.pem -new -out domain.crt 

然后将其包装到p12中:

 openssl pkcs12 -export -out rsakey.p12 -in rsakey.pem -certfile domain.crt 

但命令只是永远挂起,直到我杀了它。

.NET没有内置function来读取与证书无关的私钥(或公钥)。

最简单的解决方法是将新RSA密钥包装在自签名证书中,然后将证书和私钥放入.p12文件中。

替代方法是手动解析私钥文件/ blob并构建RSAParameters结构; 或者使用可以为您完成此操作的第三方库。

由于您的P12文件不包含X509证书,因此X509Certificate2不会将该文件解释为正确的输入。