How do you encrypt and decrypt data using ASP.NET?
How do you encrypt and decrypt data using ASP.NET?
598
13-Apr-2023
Updated on 19-Aug-2023
Gulshan Negi
19-Aug-2023Well, you can use the below code to encrypt data using ASP.NET.
using System;using System.Security.Cryptography;using System.Text;public class EncryptionHelper{public static string Encrypt(string plainText, string key, string iv){using (Aes aesAlg = Aes.Create()){aesAlg.Key = Encoding.UTF8.GetBytes(key);aesAlg.IV = Encoding.UTF8.GetBytes(iv);ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);using (MemoryStream msEncrypt = new MemoryStream()){using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)){using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)){swEncrypt.Write(plainText);}}return Convert.ToBase64String(msEncrypt.ToArray());}}}}Well, if you are looking to decrypt data using ASP.NET, then you can use the below code:
using System;using System.Security.Cryptography;using System.Text;public class EncryptionHelper{public static string Decrypt(string cipherText, string key, string iv){using (Aes aesAlg = Aes.Create()){aesAlg.Key = Encoding.UTF8.GetBytes(key);aesAlg.IV = Encoding.UTF8.GetBytes(iv);ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(cipherText))){using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)){using (StreamReader srDecrypt = new StreamReader(csDecrypt)){return srDecrypt.ReadToEnd();}}}}}}Thanks