- Let's create a new project and dive into the code to better understand encryption and decryption in ASP.NET Core:
dotnet new console -n EncryptDecryptData dotnet restore
- Now open the Program.cs file, and add the Encrypt() and Decrypt() methods, as follows:
static string Encrypt(string text, string key) { var _key = Encoding.UTF8.GetBytes(key); using (var aes = AES.Create()) { using (var encryptor = aes.CreateEncryptor(_key, aes.IV)) { using (var ms = new MemoryStream()) { using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) { using (var sw = new StreamWriter(cs)) { sw.Write(text); } } var iv = aes.IV; var encrypted = ms.ToArray(); var result = new byte[iv.Length + encrypted.Length]; Buffer.BlockCopy(iv, ...