我怎样才能正确创建RSACryptoServiceProvider
使用 RSA 私钥文件的对象?我生成了 RSA 私钥,并使用以下方法将其导出到 OSX 上的 p12 文件:
openssl genrsa -out rsakey.pem 2048
openssl pkcs12 -export -out rsakey.p12 -inkey rsakey.pem -nocerts
在我的 C# 代码(在 Windows 笔记本电脑上运行)中,我在尝试实例化时遇到错误X509Certificate2
对象,以便我可以获取私钥作为RSACryptoServiceProvider
从中取出对象:
var privateKey = new X509Certificate2(p12_file, "pass", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet).PrivateKey as RSACryptoServiceProvider;
CryptographicException:参数不正确。
下面是完整的C#代码供参考。请注意,我只是尝试按照以下文档获取私钥作为 RSACryptoServiceProvider 对象X509证书2 https://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509certificate2(v=vs.110).aspx class.
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<string, object>()
{
{ "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
但该命令会永远挂起,直到我杀死它。