using System; using System.Security.Cryptography; using System.Text; namespace FrameworkBLL.Encrypt { public interface IEncryptService { string Encrypt(string plaintext, string key = "GB5"); } public class EncryptService : IEncryptService { public string Encrypt(string plaintext, string key = "GB5") { if (string.IsNullOrEmpty(plaintext)) throw new ArgumentException("Plaintext cannot be null or empty."); if (string.IsNullOrEmpty(key)) throw new ArgumentException("Key cannot be null or empty."); // Derive 256-bit key using SHA256 (same logic as before) using SHA256 sha256 = SHA256.Create(); byte[] keyBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(key)); // 12-byte nonce (IV) – AES-GCM standard byte[] nonce = RandomNumberGenerator.GetBytes(12); byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext); byte[] ciphertext = new byte[plaintextBytes.Length]; byte[] tag = new byte[16]; // 128-bit authentication tag using (var aesGcm = new AesGcm(keyBytes)) { aesGcm.Encrypt( nonce, plaintextBytes, ciphertext, tag ); } // Final format: nonce + ciphertext + tag byte[] result = new byte[nonce.Length + ciphertext.Length + tag.Length]; Buffer.BlockCopy(nonce, 0, result, 0, nonce.Length); Buffer.BlockCopy(ciphertext, 0, result, nonce.Length, ciphertext.Length); Buffer.BlockCopy(tag, 0, result, nonce.Length + ciphertext.Length, tag.Length); return Convert.ToBase64String(result); } } }