1
To securely store and retrieve sensitive data like passwords or API keys in an ASP.NET app, you can use AES (Advanced Encryption Standard), a strong built-in encryption algorithm in .NET.
Here's a simple helper class I use for encrypting and decrypting strings:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public static class EncryptionHelper
{
private static readonly string key = "MySecretKey12345"; // Must be 16, 24, or 32 characters
public static string Encrypt(string plainText)
{
using (Aes aes = Aes.Create())
{
aes.Key = Encoding.UTF8.GetBytes(key);
aes.GenerateIV(); // Create random IV
ICryptoTransform encryptor = aes.CreateEncryptor();
using MemoryStream ms = new();
ms.Write(aes.IV, 0, aes.IV.Length); // Save IV at beginning
using CryptoStream cs = new(ms, encryptor, CryptoStreamMode.Write);
using (StreamWriter sw = new(cs))
{
sw.Write(plainText);
}
return Convert.ToBase64String(ms.ToArray()); // Return encrypted string
}
}
public static string Decrypt(string encryptedText)
{
byte[] fullCipher = Convert.FromBase64String(encryptedText);
using (Aes aes = Aes.Create())
{
byte[] iv = new byte[16];
Array.Copy(fullCipher, iv, iv.Length);
aes.Key = Encoding.UTF8.GetBytes(key);
aes.IV = iv;
ICryptoTransform decryptor = aes.CreateDecryptor();
using MemoryStream ms = new(fullCipher, 16, fullCipher.Length - 16);
using CryptoStream cs = new(ms, decryptor, CryptoStreamMode.Read);
using StreamReader sr = new(cs);
return sr.ReadToEnd(); // Return decrypted value
}
}
}
Example Usage:
// Encrypt your API key before saving
string encrypted = EncryptionHelper.Encrypt("my-real-api-key");
Console.WriteLine("Encrypted: " + encrypted);
// Decrypt it when needed
string decrypted = EncryptionHelper.Decrypt(encrypted);
Console.WriteLine("Decrypted: " + decrypted);
Important Notes:
-
Don’t hardcode the key like this in real applications: store it in environment variables, Azure Key Vault, or user secrets.
-
The above example uses a randomly generated IV (initialization vector) for better security, stored at the start of the encrypted text.
-
AES is symmetric encryption: the same key is used to encrypt and decrypt.
