Introduction
This is a simple Encryption / Decrypton program using Cryptographic Services built in .NET Framework for Symmetric Encryption.
Background
I was working on Encryptiong and Decrypting data for my project and stuck at a Cryptographic Exception "Bad Data" . This is caused due to the mismatch in the Keys used for encryption and decryption. so, come up this small piece of code that help resolve it.
Using the code
You can simply copy the CryptoEngine.cs and start using in your code. I have created static methods for Encryption and Decryption. It can be called as follows"
txtEncrypt.Text = CryptoEngine.RijndaelManagedEncryption(txtClearText.Text);
txtDecrypt.Text = CryptoEngine.RijndaelManagedDecryption(txtEncrypt.Text);
Similarly you can use the other encryption and decryption providers:
RijndaelManagedEncryption
|
RC2ProviderEncryption
|
DESProviderEncryption
|
RijndaelManagedDecryption
|
RC2ProviderDecryption
|
DESProviderDecryption
|
Points of Interest
Derive Key from Password and Initialize the Encryptor and Decryptor.
PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, null);
byte[] iv = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
byte[] key = pdb.CryptDeriveKey("DES", "SHA1", desProvider.KeySize, iv);
desProvider.Key = key;
desProvider.IV = new byte[] { 21, 22, 23, 24, 25, 26, 27, 28 };
ICryptoTransform encryptor = desProvider.CreateEncryptor(desProvider.Key, desProvider.IV);
You can extend this code to support more types of encryption supported by .NET Framework.
Here is how you can extend the code for Triple DES Provider.
static TripleDESCryptoServiceProvider tripledesProvider;
tripledesProvider = new TripleDESCryptoServiceProvider();
public static string TripleDESProviderEncryption(string plainText)
{
byte[] text = Encoding.ASCII.GetBytes(plainText);
ICryptoTransform encryptor = tripledesProvider.CreateEncryptor();
byte[] encrypted = GenericEncryptor(text, encryptor);
return Convert.ToBase64String(encrypted);
}
public static string TripleDESProviderDecryption(string plainText)
{
byte[] text = Convert.FromBase64String(plainText);
ICryptoTransform decryptor = tripledesProvider.CreateDecryptor();
string decStr = GenericDecryptor(text, decryptor);
return decStr;
}
History
This is the Initial Version of the submission.
I have updated the CryptoEngine to allow password while encrypting and decrypting, this adds a more security I believe.
References
http://blogs.msdn.com
http://msdn2.microsoft.com/en-us/library/default.aspx