feat(infrastructure): implement RsaKeyService with tests

This commit is contained in:
Joseph Doherty
2026-01-03 08:16:13 -05:00
parent 4e1523b0c0
commit 97ef3e4345
2 changed files with 146 additions and 0 deletions
@@ -0,0 +1,50 @@
// NEW/src/JdeScoping.Infrastructure/Security/RsaKeyService.cs
using System.Security.Cryptography;
using JdeScoping.Core.Interfaces;
namespace JdeScoping.Infrastructure.Security;
/// <summary>
/// RSA key service that auto-generates and persists keys.
/// </summary>
public class RsaKeyService : IRsaKeyService, IDisposable
{
private readonly RSA _rsa;
/// <summary>
/// Creates a new RSA key service.
/// </summary>
/// <param name="keyFilePath">Path to persist the private key</param>
public RsaKeyService(string keyFilePath)
{
_rsa = RSA.Create(2048);
if (File.Exists(keyFilePath))
{
var keyBytes = File.ReadAllBytes(keyFilePath);
_rsa.ImportRSAPrivateKey(keyBytes, out _);
}
else
{
var privateKey = _rsa.ExportRSAPrivateKey();
var directory = Path.GetDirectoryName(keyFilePath);
if (!string.IsNullOrEmpty(directory))
Directory.CreateDirectory(directory);
File.WriteAllBytes(keyFilePath, privateKey);
}
}
/// <inheritdoc />
public string GetPublicKeyPem()
=> _rsa.ExportSubjectPublicKeyInfoPem();
/// <inheritdoc />
public byte[] Decrypt(byte[] ciphertext)
=> _rsa.Decrypt(ciphertext, RSAEncryptionPadding.OaepSHA256);
public void Dispose()
{
_rsa.Dispose();
GC.SuppressFinalize(this);
}
}