IdentityShroud/IdentityShroud.Core/Services/DekEncryptionService.cs
eelke 07393f57fc 5-improve-encrypted-storage (#6)
Added the use of DEK's for encryption of secrets. Both the KEK's and DEK's are stored in a way that you can have multiple key of which one is active. But the others are still available for decrypting. This allows for implementing key rotation.

Co-authored-by: eelke <eelke@eelkeklein.nl>
Co-authored-by: Eelke76 <31384324+Eelke76@users.noreply.github.com>
Reviewed-on: #6
2026-02-27 17:57:42 +00:00

38 lines
No EOL
1.3 KiB
C#
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using IdentityShroud.Core.Contracts;
using IdentityShroud.Core.Security;
namespace IdentityShroud.Core.Services;
/// <summary>
///
/// </summary>
public class DekEncryptionService : IDekEncryptionService
{
// Note this array is expected to have one item in it most of the during key rotation it will have two
// until it is ensured the old key can safely be removed. More then two will work but is not really expected.
private readonly KeyEncryptionKey[] _encryptionKeys;
private KeyEncryptionKey ActiveKey => _encryptionKeys.Single(k => k.Active);
private KeyEncryptionKey GetKey(KekId keyId) => _encryptionKeys.Single(k => k.Id == keyId);
public DekEncryptionService(ISecretProvider secretProvider)
{
_encryptionKeys = secretProvider.GetKeys("master");
// if (_encryptionKey.Length != 32) // 256bit key
// throw new Exception("Key must be 256bits (32 bytes) for AES256GCM.");
}
public EncryptedDek Encrypt(ReadOnlySpan<byte> plaintext)
{
var encryptionKey = ActiveKey;
byte[] cipher = Encryption.Encrypt(plaintext, encryptionKey.Key);
return new (encryptionKey.Id, cipher);
}
public byte[] Decrypt(EncryptedDek input)
{
var encryptionKey = GetKey(input.KekId);
return Encryption.Decrypt(input.Value, encryptionKey.Key);
}
}