|
How To: Encrypt and Decrypt Data Using a Symmetric (Rijndael) Key (C#/VB.NET)
The code below demonstrates how to generate a persistent (i.e. non-random) symmetric key
using the Rijndael
(AES) algorithm
and use this key to encrypt and decrypt a text string.
The key is derived from several characteristics passed to encryption and decryption routines.
The code samples are provided in
C#
and
Visual Basic.NET.
Notes
These examples are offered for demonstration purpose only.
In a real application you may need to modify the code to make it more efficient.
For example, instead of initializing encryptor and decryptor in Encrypt and Decrypt methods,
you may want to do it once in a constructor and change the scope of both methods from
static (Shared in Visual Basic) to instance.
See also the How To Encrypt Data With Salt sample,
which explains how encryption should be implemented in production applications.
For additional information about symmetric-key encryption, check an
MSDN sample describing how to create a general purpose encryption library.
Resources
Our FREE
CipherLite.NET™
tool provides a GUI and library,
which you can use to encrypt and decrypt data
with a Rijndael key.
C# code
[printer-friendly version]
[code output]
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
public class RijndaelSimple
{
public static string Encrypt(string plainText,
string passPhrase,
string saltValue,
string hashAlgorithm,
int passwordIterations,
string initVector,
int keySize)
{
byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
PasswordDeriveBytes password = new PasswordDeriveBytes(
passPhrase,
saltValueBytes,
hashAlgorithm,
passwordIterations);
byte[] keyBytes = password.GetBytes(keySize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(
keyBytes,
initVectorBytes);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream,
encryptor,
CryptoStreamMode.Write);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherTextBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
string cipherText = Convert.ToBase64String(cipherTextBytes);
return cipherText;
}
public static string Decrypt(string cipherText,
string passPhrase,
string saltValue,
string hashAlgorithm,
int passwordIterations,
string initVector,
int keySize)
{
byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
PasswordDeriveBytes password = new PasswordDeriveBytes(
passPhrase,
saltValueBytes,
hashAlgorithm,
passwordIterations);
byte[] keyBytes = password.GetBytes(keySize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform decryptor = symmetricKey.CreateDecryptor(
keyBytes,
initVectorBytes);
MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
CryptoStream cryptoStream = new CryptoStream(memoryStream,
decryptor,
CryptoStreamMode.Read);
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
int decryptedByteCount = cryptoStream.Read(plainTextBytes,
0,
plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
string plainText = Encoding.UTF8.GetString(plainTextBytes,
0,
decryptedByteCount);
return plainText;
}
}
public class RijndaelSimpleTest
{
[STAThread]
static void Main(string[] args)
{
string plainText = "Hello, World!";
string passPhrase = "Pas5pr@se";
string saltValue = "s@1tValue";
string hashAlgorithm = "SHA1";
int passwordIterations = 2;
string initVector = "@1B2c3D4e5F6g7H8";
int keySize = 256;
Console.WriteLine(String.Format("Plaintext : {0}", plainText));
string cipherText = RijndaelSimple.Encrypt(plainText,
passPhrase,
saltValue,
hashAlgorithm,
passwordIterations,
initVector,
keySize);
Console.WriteLine(String.Format("Encrypted : {0}", cipherText));
plainText = RijndaelSimple.Decrypt(cipherText,
passPhrase,
saltValue,
hashAlgorithm,
passwordIterations,
initVector,
keySize);
Console.WriteLine(String.Format("Decrypted : {0}", plainText));
}
}
^ Back to top
VB.NET code
[printer-friendly version]
[code output]
Imports System
Imports System.IO
Imports System.Text
Imports System.Security.Cryptography
Module Module1
Public Class RijndaelSimple
Public Shared Function Encrypt(ByVal plainText As String, _
ByVal passPhrase As String, _
ByVal saltValue As String, _
ByVal hashAlgorithm As String, _
ByVal passwordIterations As Integer, _
ByVal initVector As String, _
ByVal keySize As Integer) _
As String
Dim initVectorBytes As Byte()
initVectorBytes = Encoding.ASCII.GetBytes(initVector)
Dim saltValueBytes As Byte()
saltValueBytes = Encoding.ASCII.GetBytes(saltValue)
Dim plainTextBytes As Byte()
plainTextBytes = Encoding.UTF8.GetBytes(plainText)
Dim password As PasswordDeriveBytes
password = new PasswordDeriveBytes(passPhrase, _
saltValueBytes, _
hashAlgorithm, _
passwordIterations)
Dim keyBytes As Byte()
keyBytes = password.GetBytes(keySize / 8)
Dim symmetricKey As RijndaelManaged
symmetricKey = new RijndaelManaged()
symmetricKey.Mode = CipherMode.CBC
Dim encryptor As ICryptoTransform
encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes)
Dim memoryStream As MemoryStream
memoryStream = new MemoryStream()
Dim cryptoStream As CryptoStream
cryptoStream = new CryptoStream(memoryStream, _
encryptor, _
CryptoStreamMode.Write)
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length)
cryptoStream.FlushFinalBlock()
Dim cipherTextBytes As Byte()
cipherTextBytes = memoryStream.ToArray()
memoryStream.Close()
cryptoStream.Close()
Dim cipherText As String
cipherText = Convert.ToBase64String(cipherTextBytes)
Encrypt = cipherText
End Function
Public Shared Function Decrypt(ByVal cipherText As String, _
ByVal passPhrase As String, _
ByVal saltValue As String, _
ByVal hashAlgorithm As String, _
ByVal passwordIterations As Integer, _
ByVal initVector As String, _
ByVal keySize As Integer) _
As String
Dim initVectorBytes As Byte()
initVectorBytes = Encoding.ASCII.GetBytes(initVector)
Dim saltValueBytes As Byte()
saltValueBytes = Encoding.ASCII.GetBytes(saltValue)
Dim cipherTextBytes As Byte()
cipherTextBytes = Convert.FromBase64String(cipherText)
Dim password As PasswordDeriveBytes
password = new PasswordDeriveBytes(passPhrase, _
saltValueBytes, _
hashAlgorithm, _
passwordIterations)
Dim keyBytes As Byte()
keyBytes = password.GetBytes(keySize / 8)
Dim symmetricKey As RijndaelManaged
symmetricKey = new RijndaelManaged()
symmetricKey.Mode = CipherMode.CBC
Dim decryptor As ICryptoTransform
decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes)
Dim memoryStream As MemoryStream
memoryStream = new MemoryStream(cipherTextBytes)
Dim cryptoStream As CryptoStream
cryptoStream = new CryptoStream(memoryStream, _
decryptor, _
CryptoStreamMode.Read)
Dim plainTextBytes As Byte()
ReDim plainTextBytes(cipherTextBytes.Length)
Dim decryptedByteCount As Integer
decryptedByteCount = cryptoStream.Read(plainTextBytes, _
0, _
plainTextBytes.Length)
memoryStream.Close()
cryptoStream.Close()
Dim plainText As String
plainText = Encoding.UTF8.GetString(plainTextBytes, _
0, _
decryptedByteCount)
Decrypt = plainText
End Function
End Class
Sub Main()
Dim plainText As String
Dim cipherText As String
Dim passPhrase As String
Dim saltValue As String
Dim hashAlgorithm As String
Dim passwordIterations As Integer
Dim initVector As String
Dim keySize As Integer
plainText = "Hello, World!"
passPhrase = "Pas5pr@se"
saltValue = "s@1tValue"
hashAlgorithm = "SHA1"
passwordIterations = 2
initVector = "@1B2c3D4e5F6g7H8"
keySize = 256
Console.WriteLine(String.Format("Plaintext : {0}", plainText))
cipherText = RijndaelSimple.Encrypt(plainText, _
passPhrase, _
saltValue, _
hashAlgorithm, _
passwordIterations, _
initVector, _
keySize)
Console.WriteLine(String.Format("Encrypted : {0}", cipherText))
plainText = RijndaelSimple.Decrypt(cipherText, _
passPhrase, _
saltValue, _
hashAlgorithm, _
passwordIterations, _
initVector, _
keySize)
Console.WriteLine(String.Format("Decrypted : {0}", plainText))
End Sub
End Module
^ Back to top
Code Output
Plaintext : Hello, World!
Encrypted : Pr4prQGpaQ/XADxgEaVSfA==
Decrypted : Hello, World!
^ Back to top
|