feat(infrastructure): implement RsaKeyService with tests
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user