using System.Security.Cryptography; using System.Text; namespace CartriX.Shared.Classes { public static class CryptoHelper { private const int SaltSize = 16; private const int KeySize = 32; private const int Iterations = 100_000; public static string Encrypt(string plainText) { byte[] salt = RandomNumberGenerator.GetBytes(SaltSize); using var aes = Aes.Create(); aes.GenerateIV(); aes.Key = Rfc2898DeriveBytes.Pbkdf2("123", salt, Iterations, HashAlgorithmName.SHA256, KeySize); using var encryptor = aes.CreateEncryptor(); byte[] plainBytes = Encoding.UTF8.GetBytes(plainText); byte[] encryptedBytes = encryptor.TransformFinalBlock(plainBytes, 0, plainBytes.Length); // Salt + IV + CipherText byte[] result = new byte[salt.Length + aes.IV.Length + encryptedBytes.Length]; Buffer.BlockCopy(salt, 0, result, 0, salt.Length); Buffer.BlockCopy(aes.IV, 0, result, salt.Length, aes.IV.Length); Buffer.BlockCopy(encryptedBytes, 0, result, salt.Length + aes.IV.Length, encryptedBytes.Length); return Convert.ToBase64String(result); } public static string Decrypt(string encryptedText) { byte[] fullData = Convert.FromBase64String(encryptedText); byte[] salt = fullData[..SaltSize]; byte[] iv = fullData[SaltSize..(SaltSize + 16)]; byte[] cipherText = fullData[(SaltSize + 16)..]; using var aes = Aes.Create(); aes.Key = Rfc2898DeriveBytes.Pbkdf2("123", salt, Iterations, HashAlgorithmName.SHA256, KeySize); aes.IV = iv; using var decryptor = aes.CreateDecryptor(); byte[] decryptedBytes = decryptor.TransformFinalBlock(cipherText, 0, cipherText.Length); return Encoding.UTF8.GetString(decryptedBytes); } } }