2026-02-27 17:57:42 +00:00
|
|
|
using IdentityShroud.Core.Contracts;
|
|
|
|
|
using IdentityShroud.Core.Model;
|
|
|
|
|
using IdentityShroud.Core.Security;
|
|
|
|
|
|
|
|
|
|
namespace IdentityShroud.Core.Services;
|
|
|
|
|
|
|
|
|
|
public class DataEncryptionService(
|
|
|
|
|
IDekEncryptionService dekCryptor) : IDataEncryptionService
|
|
|
|
|
{
|
2026-03-16 19:15:04 +01:00
|
|
|
public EncryptedValue Encrypt(RealmDek dek, ReadOnlySpan<byte> plain)
|
2026-02-27 17:57:42 +00:00
|
|
|
{
|
|
|
|
|
var key = dekCryptor.Decrypt(dek.KeyData);
|
2026-03-16 19:15:04 +01:00
|
|
|
byte[] cipher = Encryption.Encrypt(plain, key);
|
|
|
|
|
return new (dek.Id, cipher);
|
2026-02-27 17:57:42 +00:00
|
|
|
}
|
|
|
|
|
|
2026-03-16 19:15:04 +01:00
|
|
|
public byte[] Decrypt(IReadOnlyList<RealmDek> deks, EncryptedValue input)
|
2026-02-27 17:57:42 +00:00
|
|
|
{
|
2026-03-16 19:15:04 +01:00
|
|
|
// Note a missing key SHOULD not happen. If it does happen something has seriously gone wrong like
|
|
|
|
|
// - Old key removed before migration completed (should not be possible)
|
|
|
|
|
// - Wrong keyset because of programming error.
|
|
|
|
|
var dek = deks.SingleOrDefault(d => d.Id == input.DekId)
|
|
|
|
|
?? throw new InvalidOperationException("Required key not found");
|
2026-02-27 17:57:42 +00:00
|
|
|
var key = dekCryptor.Decrypt(dek.KeyData);
|
2026-03-16 19:15:04 +01:00
|
|
|
return Encryption.Decrypt(input.Value, key);
|
2026-02-27 17:57:42 +00:00
|
|
|
}
|
|
|
|
|
}
|