| | | 1 | | using System.Security.Cryptography; |
| | | 2 | | |
| | | 3 | | namespace NLightning.Node.Helpers; |
| | | 4 | | |
| | | 5 | | public static class AesGcmHelper |
| | | 6 | | { |
| | | 7 | | private const int AesGcmTagSize = 16; |
| | | 8 | | |
| | | 9 | | private static byte[] DeriveKey(string password, byte[] salt) |
| | | 10 | | { |
| | 0 | 11 | | using var kdf = new Rfc2898DeriveBytes(password, salt, 100_000, HashAlgorithmName.SHA256); |
| | 0 | 12 | | return kdf.GetBytes(32); |
| | 0 | 13 | | } |
| | | 14 | | |
| | | 15 | | public static byte[] Encrypt(byte[] plaintext, string password) |
| | | 16 | | { |
| | 0 | 17 | | var salt = RandomNumberGenerator.GetBytes(AesGcmTagSize); |
| | 0 | 18 | | var key = DeriveKey(password, salt); |
| | 0 | 19 | | var nonce = RandomNumberGenerator.GetBytes(12); |
| | 0 | 20 | | var tag = new byte[AesGcmTagSize]; |
| | 0 | 21 | | var ciphertext = new byte[plaintext.Length]; |
| | | 22 | | |
| | 0 | 23 | | using (var aes = new AesGcm(key, AesGcmTagSize)) |
| | | 24 | | { |
| | 0 | 25 | | aes.Encrypt(nonce, plaintext, ciphertext, tag); |
| | 0 | 26 | | } |
| | | 27 | | |
| | 0 | 28 | | return salt.Concat(nonce).Concat(tag).Concat(ciphertext).ToArray(); |
| | | 29 | | } |
| | | 30 | | |
| | | 31 | | public static byte[] Decrypt(byte[] encrypted, string password) |
| | | 32 | | { |
| | 0 | 33 | | var salt = encrypted.AsSpan(0, AesGcmTagSize).ToArray(); |
| | 0 | 34 | | var nonce = encrypted.AsSpan(AesGcmTagSize, 12).ToArray(); |
| | 0 | 35 | | var tag = encrypted.AsSpan(28, AesGcmTagSize).ToArray(); |
| | 0 | 36 | | var ciphertext = encrypted.AsSpan(44).ToArray(); |
| | 0 | 37 | | var key = DeriveKey(password, salt); |
| | 0 | 38 | | var plaintext = new byte[ciphertext.Length]; |
| | | 39 | | |
| | 0 | 40 | | using var aes = new AesGcm(key, AesGcmTagSize); |
| | 0 | 41 | | aes.Decrypt(nonce, ciphertext, tag, plaintext); |
| | | 42 | | |
| | 0 | 43 | | return plaintext; |
| | 0 | 44 | | } |
| | | 45 | | } |