Reworked encryption to use less heap allocated buffers for secrets.

Also some work on plugin system.
This commit is contained in:
eelke 2026-08-18 07:40:24 +02:00
parent 8782ef39c6
commit 054754f553
42 changed files with 1452 additions and 242 deletions

View file

@ -1,3 +1,4 @@
using System.Security.Cryptography;
using IdentityShroud.Core.Contracts;
using IdentityShroud.Core.Model;
using IdentityShroud.Core.Security;
@ -9,9 +10,17 @@ public class DataEncryptionService(
{
public EncryptedValue Encrypt(RealmDek dek, ReadOnlySpan<byte> plain)
{
var key = dekCryptor.Decrypt(dek.KeyData);
byte[] cipher = Encryption.Encrypt(plain, key);
return new (dek.Id, cipher);
Span<byte> key = stackalloc byte[dekCryptor.GetDecryptedSize(dek.KeyData)];
try
{
dekCryptor.Decrypt(dek.KeyData, key);
byte[] cipher = Encryption.Encrypt(plain, key);
return new (dek.Id, cipher);
}
finally
{
CryptographicOperations.ZeroMemory(key);
}
}
public byte[] Decrypt(IReadOnlyList<RealmDek> deks, EncryptedValue input)
@ -20,8 +29,19 @@ public class DataEncryptionService(
// - 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");
var key = dekCryptor.Decrypt(dek.KeyData);
return Encryption.Decrypt(input.Value, key);
?? throw new InvalidOperationException("Required key not found");
Span<byte> key = stackalloc byte[dekCryptor.GetDecryptedSize(dek.KeyData)];
try
{
dekCryptor.Decrypt(dek.KeyData, key);
byte[] output = new byte[Encryption.GetDecryptedLength(input.Value)];
Encryption.Decrypt(input.Value, key, output);
return output;
}
finally
{
CryptographicOperations.ZeroMemory(key);
}
}
}