| | | 1 | | using System.Security.Cryptography; |
| | | 2 | | using Microsoft.Extensions.Options; |
| | | 3 | | |
| | | 4 | | namespace Elsa.Secrets.Services; |
| | | 5 | | |
| | 39 | 6 | | public class DefaultSecretValueProtector(IOptions<SecretsOptions> options) : ISecretValueProtector |
| | | 7 | | { |
| | | 8 | | private const int NonceSize = 12; |
| | | 9 | | private const int TagSize = 16; |
| | | 10 | | |
| | | 11 | | public string Protect(string value) |
| | | 12 | | { |
| | 31 | 13 | | var nonce = RandomNumberGenerator.GetBytes(NonceSize); |
| | 31 | 14 | | var plaintext = System.Text.Encoding.UTF8.GetBytes(value); |
| | 31 | 15 | | var ciphertext = new byte[plaintext.Length]; |
| | 31 | 16 | | var tag = new byte[TagSize]; |
| | | 17 | | |
| | 31 | 18 | | using var aes = new AesGcm(GetKey(), TagSize); |
| | 27 | 19 | | aes.Encrypt(nonce, plaintext, ciphertext, tag); |
| | | 20 | | |
| | 27 | 21 | | return string.Join(".", "v1", Convert.ToBase64String(nonce), Convert.ToBase64String(tag), Convert.ToBase64String |
| | 27 | 22 | | } |
| | | 23 | | |
| | | 24 | | public string Unprotect(string protectedValue) |
| | | 25 | | { |
| | 7 | 26 | | var parts = protectedValue.Split('.'); |
| | 7 | 27 | | if (parts.Length != 4 || parts[0] != "v1") |
| | 3 | 28 | | throw new InvalidOperationException("The protected secret payload is not supported."); |
| | | 29 | | |
| | 4 | 30 | | var nonce = Convert.FromBase64String(parts[1]); |
| | 3 | 31 | | var tag = Convert.FromBase64String(parts[2]); |
| | 3 | 32 | | var ciphertext = Convert.FromBase64String(parts[3]); |
| | 3 | 33 | | var plaintext = new byte[ciphertext.Length]; |
| | | 34 | | |
| | 3 | 35 | | using var aes = new AesGcm(GetKey(), TagSize); |
| | 3 | 36 | | aes.Decrypt(nonce, ciphertext, tag, plaintext); |
| | | 37 | | |
| | 3 | 38 | | return System.Text.Encoding.UTF8.GetString(plaintext); |
| | 3 | 39 | | } |
| | | 40 | | |
| | | 41 | | private byte[] GetKey() |
| | | 42 | | { |
| | 34 | 43 | | var key = options.Value.EncryptionKey; |
| | 34 | 44 | | if (key == null || key.Length == 0) |
| | 2 | 45 | | throw new InvalidOperationException("Elsa Secrets encryption key is not configured. Configure SecretsOptions |
| | | 46 | | |
| | 32 | 47 | | if (key.Length is not (16 or 24 or 32)) |
| | 2 | 48 | | throw new InvalidOperationException("Elsa Secrets encryption key must be exactly 16, 24, or 32 bytes."); |
| | | 49 | | |
| | 30 | 50 | | return key; |
| | | 51 | | } |
| | | 52 | | } |