How to do it...

  1. 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 
  1. 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, ...

Get ASP.NET Core MVC 2.0 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.