2026-07-17 20:07:03 +00:00
|
|
|
using System.Text;
|
2026-07-22 19:43:13 +00:00
|
|
|
using Heimdall.Application.Common;
|
2026-07-17 20:07:03 +00:00
|
|
|
using Microsoft.AspNetCore.DataProtection;
|
|
|
|
|
|
|
|
|
|
namespace Heimdall.Infrastructure.Security;
|
|
|
|
|
|
|
|
|
|
public sealed class DataProtectorCredentialProtector : ICredentialProtector
|
|
|
|
|
{
|
|
|
|
|
private readonly IDataProtector _protector;
|
|
|
|
|
|
|
|
|
|
public DataProtectorCredentialProtector(IDataProtectionProvider provider)
|
|
|
|
|
{
|
|
|
|
|
_protector = provider.CreateProtector("Heimdall.CameraCredentials.v1");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public string Encrypt(string plaintext)
|
|
|
|
|
{
|
|
|
|
|
if (string.IsNullOrEmpty(plaintext))
|
|
|
|
|
return string.Empty;
|
|
|
|
|
|
|
|
|
|
var protectedBytes = _protector.Protect(Encoding.UTF8.GetBytes(plaintext));
|
|
|
|
|
return Convert.ToBase64String(protectedBytes);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public string Decrypt(string ciphertext)
|
|
|
|
|
{
|
|
|
|
|
if (string.IsNullOrEmpty(ciphertext))
|
|
|
|
|
return string.Empty;
|
|
|
|
|
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
var protectedBytes = Convert.FromBase64String(ciphertext);
|
|
|
|
|
var unprotectedBytes = _protector.Unprotect(protectedBytes);
|
|
|
|
|
return Encoding.UTF8.GetString(unprotectedBytes);
|
|
|
|
|
}
|
2026-07-26 19:49:42 +00:00
|
|
|
catch (Exception) when (!string.IsNullOrEmpty(ciphertext))
|
2026-07-17 20:07:03 +00:00
|
|
|
{
|
|
|
|
|
// If data is not encrypted (plaintext fallback for migration),
|
|
|
|
|
// return as-is. This prevents data loss if the protector is
|
|
|
|
|
// added to a database that already has plaintext values.
|
|
|
|
|
return ciphertext;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|