In C#, you can implement encryption and decryption using the System.Security.Cryptography namespace. Below, you'll find an example that demonstrates how to use AES (Advanced Encryption Standard) for this purpose.
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public class AesEncryption
{
private static readonly string key = "your-encryption-key"; // Use a safe key here
public static string Encrypt(string plainText)
{
using (Aes aes = Aes.Create())
{
aes.Key = Encoding.UTF8.GetBytes(key);
aes.GenerateIV();
using (MemoryStream ms = new MemoryStream())
{
ms.Write(aes.IV, 0, aes.IV.Length);
using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
using (StreamWriter sw = new StreamWriter(cs))
{
sw.Write(plainText);
}
}
return Convert.ToBase64String(ms.ToArray());
}
}
}
public static string Decrypt(string cipherText)
{
using (Aes aes = Aes.Create())
{
byte[] fullCipher = Convert.FromBase64String(cipherText);
byte[] iv = new byte[aes.BlockSize / 8];
byte[] cipher = new byte[fullCipher.Length - iv.Length];
Array.Copy(fullCipher, iv, iv.Length);
Array.Copy(fullCipher, iv.Length, cipher, 0, cipher.Length);
aes.Key = Encoding.UTF8.GetBytes(key);
aes.IV = iv;
using (MemoryStream ms = new MemoryStream(cipher))
{
using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Read))
{
using (StreamReader sr = new StreamReader(cs))
{
return sr.ReadToEnd();
}
}
}
}
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?