If you have to use Symmetric Encryption in your ASP.NET project you can use the class described in the article How to create symmetric encryption utility class in ASP.NET in C#. To illustrate this you can create a page that permits you to generate a key and enter clear-text data through a text box. You can output the encrypted data through Convert.ToBase64String(). For decryption you should call Convert.FromBase64String() to get the encrypted bytes back and pass them into the DecryptData method.
private string KeyFileName;
private string AlgorithmName = “RC2“;
protected void Page_Load(object sender, EventArgs e)
{
SymmetricEncryptionUtility.AlgorithmName = AlgorithmName;
KeyFileName = Server.MapPath(“./”) + “\\symmetric_key.config”;
}
protected void GenerateKeyCommand_Click(object sender, EventArgs e)
{
SymmetricEncryptionUtility.ProtectKey = EncryptKeyCheck.Checked;
SymmetricEncryptionUtility.GenerateKey(KeyFileName);
Response.Write(“Key generated successfully!”);
}
protected void EncryptCommand_Click(object sender, EventArgs e)
{
// Check for encryption key
if (!File.Exists(KeyFileName))
{
Response.Write(“Missing encryption key. Please generate key!”);
}
byte[] data = SymmetricEncryptionUtility.EncryptData(ClearDataText.Text, KeyFileName);
EncryptedDataText.Text = Convert.ToBase64String(data);
}
protected void DecryptCommand_Click(object sender, EventArgs e)
{
// Check for encryption key
if (!File.Exists(KeyFileName))
{
Response.Write(“Missing encryption key. Please generate key!”);
}
byte[] data = Convert.FromBase64String(EncryptedDataText.Text);
ClearDataText.Text = SymmetricEncryptionUtility.DecryptData(data, KeyFileName);
}
The next picture presents the results: