Crie o objeto RSACryptoServiceProvider usando o arquivo de chave privada RSA em C #
Como posso criar corretamente oRSACryptoServiceProvider
objeto usando um arquivo de chave privada RSA? Gerei uma chave privada RSA e a exportei para um arquivo p12 no OSX usando os métodos:
openssl genrsa -out rsakey.pem 2048
openssl pkcs12 -export -out rsakey.p12 -inkey rsakey.pem -nocerts
No meu código C #, que é executado em um laptop Windows, estou recebendo um erro ao tentar instanciar oX509Certificate2
objeto para que eu possa pegar a chave privada como umRSACryptoServiceProvider
objeto fora dele:
var privateKey = new X509Certificate2(p12_file, "pass", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet).PrivateKey as RSACryptoServiceProvider;
CryptographicException: O parâmetro está incorreto.
Abaixo está o código C # inteiro para referência. Observe que estou apenas tentando obter a chave privada como um objeto RSACryptoServiceProvider, seguindo os documentos para oX509Certificate2 classe.
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;
}
}
}
ATUALIZAÇÃO: tentei criar meu certificado autoassinado usando
openssl req -key rsakey.pem -new -out domain.crt
e depois envolvê-lo em uma p12:
openssl pkcs12 -export -out rsakey.p12 -in rsakey.pem -certfile domain.crt
mas o comando permanece para sempre até que eu o mate.