| | 1 | | using System.Security.Cryptography; |
| | 2 | | using System.Text.Json; |
| | 3 | |
|
| | 4 | | namespace Common; |
| | 5 | |
|
| | 6 | | public static class Aes256 |
| | 7 | | { |
| | 8 | | public static Aes256<T> Encrypt<T>(in T target, in AesKey key) |
| 4 | 9 | | { |
| 4 | 10 | | using var aes = new AesGcm(key.Value); |
| | 11 | |
|
| 4 | 12 | | var plaintextBytes = JsonSerializer.SerializeToUtf8Bytes(target); |
| 4 | 13 | | var body = new byte[plaintextBytes.Length]; |
| 4 | 14 | | var tag = new byte[AesGcm.TagByteSizes.MaxSize]; |
| 4 | 15 | | var iv = RandomNumberGenerator.GetBytes(AesGcm.NonceByteSizes.MaxSize); |
| | 16 | |
|
| 4 | 17 | | aes.Encrypt(iv, plaintextBytes, body, tag); |
| | 18 | |
|
| 4 | 19 | | return new Aes256<T>(body, iv, tag); |
| 4 | 20 | | } |
| | 21 | | } |
| | 22 | |
|
| | 23 | | public record Aes256<T>(byte[] Body, byte[] IV, byte[] Tag) |
| | 24 | | { |
| | 25 | | public static implicit operator Aes256<T>(in (T Target, AesKey Key) v) => |
| | 26 | | Aes256.Encrypt(v.Target, v.Key); |
| | 27 | |
|
| | 28 | | public T Decrypt(in AesKey key) |
| | 29 | | { |
| | 30 | | using var aes = new AesGcm(key.Value); |
| | 31 | |
|
| | 32 | | var plaintextBytes = new byte[Body.Length]; |
| | 33 | | aes.Decrypt(IV, Body, Tag, plaintextBytes); |
| | 34 | |
|
| | 35 | | return JsonSerializer.Deserialize<T>(plaintextBytes)!; |
| | 36 | | } |
| | 37 | | } |