| | 1 | | using System.Security.Cryptography; |
| | 2 | | using System.Text; |
| | 3 | | using Cff.Effect.Abstractions; |
| | 4 | | using Cff.Effect.Abstractions.Domain; |
| | 5 | |
|
| | 6 | | namespace Cff.Effect.Aes; |
| | 7 | |
|
| 4 | 8 | | internal readonly record struct Aes(AesKey AesKey) : IAes |
| | 9 | | { |
| | 10 | | public (byte[] Body, byte[] Nonce, byte[] Tag) Encrypt(string source) |
| 1 | 11 | | { |
| 1 | 12 | | using var aes = new AesGcm(AesKey.Value); |
| | 13 | |
|
| 1 | 14 | | var nonce = new byte[AesGcm.NonceByteSizes.MaxSize]; |
| 1 | 15 | | RandomNumberGenerator.Fill(nonce); |
| | 16 | |
|
| 1 | 17 | | var plaintextBytes = Encoding.UTF8.GetBytes(source); |
| 1 | 18 | | var body = new byte[plaintextBytes.Length]; |
| 1 | 19 | | var tag = new byte[AesGcm.TagByteSizes.MaxSize]; |
| | 20 | |
|
| 1 | 21 | | aes.Encrypt(nonce, plaintextBytes, body, tag); |
| | 22 | |
|
| 1 | 23 | | return (body, nonce, tag); |
| 1 | 24 | | } |
| | 25 | |
|
| | 26 | | public string Decrypt(byte[] body, byte[] nonce, byte[] tag) |
| 1 | 27 | | { |
| 1 | 28 | | using var aes = new AesGcm(AesKey.Value); |
| 1 | 29 | | var plaintextBytes = new byte[body.Length]; |
| 1 | 30 | | aes.Decrypt(nonce, body, tag, plaintextBytes); |
| | 31 | |
|
| 1 | 32 | | return Encoding.UTF8.GetString(plaintextBytes); |
| 1 | 33 | | } |
| | 34 | | } |
| | 35 | |
|