How do I implement encryption and decryption

In C#, you can implement encryption and decryption using the System.Security.Cryptography namespace. Below, you'll find an example that demonstrates how to use AES (Advanced Encryption Standard) for this purpose.

Encryption and Decryption Example

using System; using System.IO; using System.Security.Cryptography; using System.Text; public class AesEncryption { private static readonly string key = "your-encryption-key"; // Use a safe key here public static string Encrypt(string plainText) { using (Aes aes = Aes.Create()) { aes.Key = Encoding.UTF8.GetBytes(key); aes.GenerateIV(); using (MemoryStream ms = new MemoryStream()) { ms.Write(aes.IV, 0, aes.IV.Length); using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write)) { using (StreamWriter sw = new StreamWriter(cs)) { sw.Write(plainText); } } return Convert.ToBase64String(ms.ToArray()); } } } public static string Decrypt(string cipherText) { using (Aes aes = Aes.Create()) { byte[] fullCipher = Convert.FromBase64String(cipherText); byte[] iv = new byte[aes.BlockSize / 8]; byte[] cipher = new byte[fullCipher.Length - iv.Length]; Array.Copy(fullCipher, iv, iv.Length); Array.Copy(fullCipher, iv.Length, cipher, 0, cipher.Length); aes.Key = Encoding.UTF8.GetBytes(key); aes.IV = iv; using (MemoryStream ms = new MemoryStream(cipher)) { using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Read)) { using (StreamReader sr = new StreamReader(cs)) { return sr.ReadToEnd(); } } } } } }

Encryption Decryption Aes C# Security Cryptography