Hi all,
I have an encryption class that encrypts and decrypts password using
TripleDESCrypto ServiceProvider . It was written originally in framework
1.0 and been working fine. And those passwords are stored in my SQL
server.
Now I need to migrate my application to framework 2.0. I use this same
class with framework 2.0 library to decrypt the passwords from database
(of course, they were encrypted in 1.0) but getting "Bad Data"
exception. The wierd thing is that, in 2.0 environment, it can encrypt
a new password and decrypt it back without any problem. It just cannot
decrypt the ones which were encrypted in 1.0.
Anyone experienced this problem before? Any ideas will be very
appreciated!!
Hans
I am also attaching the class as follows:
using System;
using System.IO;
using System.Security .Cryptography;
using System.Text;
namespace test
{
/// <summary>
/// Summary description for EncryptionManag er.
/// </summary>
public class EncryptionManag er
{
public const int Encryption = 0;
public const int Decryption = 1;
private EncryptionManag er()
{
}
public static string Encrypt(string toEncrypt, string key)
{
UnicodeEncoding encoder = new UnicodeEncoding ();
return encoder.GetStri ng(ParseBytes(e ncoder.GetBytes (toEncrypt),
key, Encryption));
}
public static string Decrypt(string toDecrypt, string key)
{
UnicodeEncoding encoder = new UnicodeEncoding ();
return encoder.GetStri ng(ParseBytes(e ncoder.GetBytes (toDecrypt),
key, Decryption));
}
private static byte[] ParseBytes (byte[] data, string key, int
direction)
{
TripleDES des = new TripleDESCrypto ServiceProvider () ;
des.IV = new byte[8];
//init stream to write / read data
MemoryStream memStream = new MemoryStream();
PasswordDeriveB ytes derivedBytes = new PasswordDeriveB ytes(key, new
byte[0]);
des.Key = derivedBytes.Cr yptDeriveKey("R C2", "MD5", 128, new
byte[8]);
//set transform according to direction
ICryptoTransfor m transform;
if (direction == Encryption)
{
transform = des.CreateEncry ptor();
}
else
{
transform = des.CreateDecry ptor();
}
CryptoStream cryptoStream = new CryptoStream (memStream,
transform,
CryptoStreamMod e.Write);
cryptoStream.Wr ite (data, 0, data.Length);
cryptoStream.Fl ushFinalBlock() ;
//get the length of the encrypted data...
byte[] encodedResult = new byte[memStream.Lengt h];
memStream.Posit ion = 0;
memStream.Read( encodedResult, 0, encodedResult.L ength);
memStream.Close ();
cryptoStream.Cl ose();
return encodedResult;
}
public static string GenerateKey()
{
UnicodeEncoding encoder = new UnicodeEncoding ();
TripleDES des = new TripleDESCrypto ServiceProvider ();
return encoder.GetStri ng(des.Key);
}
}
}