Reputation: 17
I am trying to translate this C# .NET 6.0 code to run on .NET 4.8. I am trying to get a token using a RSA private key pem file. But I didn't succeed.
Please, can someone help me ?
I have a problem with the ImportRSAPrivateKey
method. It doesn't exist in .NET 4.8. How can I change this ImportRSAPrivateKey
method ?
It is an important method but Is there any other package in .NET 4.8 that can help to change this method?
using System;
using System.IO;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
namespace toto.Auth
{
public class AuthRequestService
{
private const string DATE_PATTERN = "yyyy-MM-ddTHH:mm:ss.fffK";
private const string ODC_AUTH_URL = "https://myurl/auth";
private FileInfo certFile;
private string partnerId;
private RSA privateKey;
private JsonSerializerOptions jsonOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
public AuthRequestService(string certFilePath, string partnerId)
{
this.certFile = new FileInfo(certFilePath);
this.privateKey = ReadPKCS8PrivateKey(certFile);
this.partnerId = partnerId;
}
public string GetTokenForRPPS(string rpps)
{
var timeStamp = DateTime.UtcNow.ToString(DATE_PATTERN);
var body = new AuthRequestDTO(partnerId, rpps, timeStamp);
string result = string.Empty;
try
{
using (var privateSignature = new RSACryptoServiceProvider())
{
privateSignature.ImportRSAPrivateKey(privateKey.ExportRSAPrivateKey(), out _);
Console.WriteLine("unsigned json:");
var unsignedJson = JsonSerializer.Serialize(body, jsonOptions);
Console.WriteLine(unsignedJson);
var signatureBytes = privateSignature.SignData(Encoding.UTF8.GetBytes(unsignedJson), HashAlgorithmName.SHA512, RSASignaturePadding.Pkcs1);
string signB64 = Convert.ToBase64String(signatureBytes);
body.Signature = signB64;
string signedPayload = JsonSerializer.Serialize(body, jsonOptions);
Console.WriteLine("signed json:");
Console.WriteLine(signedPayload);
using (HttpClient httpClient = new HttpClient())
{
var httpRequest = new HttpRequestMessage(HttpMethod.Post, ODC_AUTH_URL)
{
Content = new StringContent(signedPayload, Encoding.UTF8, "application/json")
};
var response = httpClient.SendAsync(httpRequest).Result;
result = response.Content.ReadAsStringAsync().Result;
}
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
return result;
}
protected RSA ReadPKCS8PrivateKey(FileInfo file)
{
string key = File.ReadAllText(file.FullName);
string privateKeyPEM = key
.Replace("-----BEGIN RSA PRIVATE KEY-----", "")
.Replace(Environment.NewLine, "")
.Replace("-----END RSA PRIVATE KEY-----", "");
byte[] encoded = Convert.FromBase64String(privateKeyPEM);
return RSA.Create();
}
}
}
Upvotes: 0
Views: 113