---
title: "How do you encrypt and decrypt data using ASP.NET?"  
description: "How do you encrypt and decrypt data using ASP.NET?"  
author: "Ravi Vishwakarma"  
published: 2023-04-13  
updated: 2023-08-19  
canonical: https://www.mindstick.com/forum/157781/how-do-you-encrypt-and-decrypt-data-using-asp-dot-net  
category: "asp.net"  
tags: ["asp.net mvc"]  
reading_time: 1 minute  

---

# How do you encrypt and decrypt data using ASP.NET?

How do you encrypt and decrypt [data](https://www.mindstick.com/articles/13050/salesforce-aiming-to-dominate-predictive-analytics-with-data-science) using [ASP.NET](https://www.mindstick.com/articles/934/default-folders-available-inside-the-asp-dot-net-application-folder)?

## Replies

### Reply by Gulshan Negi

Well, 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


---

Original Source: https://www.mindstick.com/forum/157781/how-do-you-encrypt-and-decrypt-data-using-asp-dot-net

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
