How to Use Rijndael ManagedEncryption with C#






4.87/5 (16 votes)
To encrypt or not to encrypt with C# .NET
Introduction
This example shows you how to use the RijndaelManaged
class that is available in .NET since version 1.1.
Using the Code
Using encryption with .NET is very easy. For this, we use the RijnDaelManaged
class. We need to initialize this class by calling
after the class is created we have to create our secret key by creating a class called NewRijndaelManaged(
)Rfc2898DeriveBytes
like this Rfc2898DeriveBytes(Inputkey, salt)
. The constructor on this class needs 2 input parameters, a password and a salt key. In the code below, we use two GUIDs as the pasword and salt key.
When we call the EncryptRijndael(string text)
function with the following text "My super secret text
", this will result in the following string
"sBJUwV7Vo+ou9kYds6HfqFRHLcGf5MLiRUZk8ICt9h8=
" to decrypt this string
we call the DecryptRijndael(string cipherText)
which will give back the original text. To make everything super simple, I wrapped everything up in a simple static
class that does all the work (the little that needs to be done).
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
namespace RijndaelManagedEncryption
{
public class RijndaelManagedEncryption
{
#region Consts
/// <summary>
/// Change the Inputkey GUID when you use this code in your own program.
/// Keep this inputkey very safe and prevent someone from decoding it some way!!
/// </summary>
internal const string Inputkey = "560A18CD-6346-4CF0-A2E8-671F9B6B9EA9";
#endregion
#region Rijndael Encryption
/// <summary>
/// Encrypt the given text and give the byte array back as a BASE64 string
/// </summary>
/// <param name="text" />The text to encrypt
/// <param name="salt" />The pasword salt
/// <returns>The encrypted text</returns>
public static string EncryptRijndael(string text, string salt)
{
if (string.IsNullOrEmpty(text))
throw new ArgumentNullException("text");
var aesAlg = NewRijndaelManaged(salt);
var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
var msEncrypt = new MemoryStream();
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
using (var swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(text);
}
return Convert.ToBase64String(msEncrypt.ToArray());
}
#endregion
#region Rijndael Dycryption
/// <summary>
/// Checks if a string is base64 encoded
/// </summary>
/// <param name="base64String" />The base64 encoded string
/// <returns>Base64 encoded stringt</returns>
public static bool IsBase64String(string base64String)
{
base64String = base64String.Trim();
return (base64String.Length%4 == 0) &&
Regex.IsMatch(base64String, @"^[a-zA-Z0-9\+/]*={0,3}$", RegexOptions.None);
}
/// <summary>
/// Decrypts the given text
/// </summary>
/// <param name="cipherText" />The encrypted BASE64 text
/// <param name="salt" />The pasword salt
/// <returns>The decrypted text</returns>
public static string DecryptRijndael(string cipherText, string salt)
{
if (string.IsNullOrEmpty(cipherText))
throw new ArgumentNullException("cipherText");
if (!IsBase64String(cipherText))
throw new Exception("The cipherText input parameter is not base64 encoded");
string text;
var aesAlg = NewRijndaelManaged(salt);
var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
var cipher = Convert.FromBase64String(cipherText);
using (var msDecrypt = new MemoryStream(cipher))
{
using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (var srDecrypt = new StreamReader(csDecrypt))
{
text = srDecrypt.ReadToEnd();
}
}
}
return text;
}
#endregion
#region NewRijndaelManaged
/// <summary>
/// Create a new RijndaelManaged class and initialize it
/// </summary>
/// <param name="salt" />The pasword salt
/// <returns></returns>
private static RijndaelManaged NewRijndaelManaged(string salt)
{
if (salt == null) throw new ArgumentNullException("salt");
var saltBytes = Encoding.ASCII.GetBytes(salt);
var key = new Rfc2898DeriveBytes(Inputkey, saltBytes);
var aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8);
return aesAlg;
}
#endregion
}
}
To test the above class, I added an example program that looks like this:
History
- 2013-12-31 - First version
- 2013-01-02 - Version 1.1, changed the code so a random generated salt could be used