tags:

views:

744

answers:

2

Take the Following code:

DESCryptoServiceProvider des = new DESCryptoServiceProvider();
des.Key = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};
ICryptoTransform encryptor = des.CreateEncryptor();
// encrypt
byte[] x = UTF8Encoding.UTF8.GetBytes("thisIsATEST");
byte[] enc = encryptor.TransformFinalBlock(x, 0, x.Length);
string savedValue = Convert.ToBase64String(enc);



DESCryptoServiceProvider des1 = new DESCryptoServiceProvider();
des1.Key = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};
ICryptoTransform decryptor = des1.CreateDecryptor();
byte[] y = Convert.FromBase64String(savedValue);
// decrypt
byte[] originalAgain = decryptor.TransformFinalBlock(y, 0, y.Length);
System.Text.ASCIIEncoding e = new System.Text.ASCIIEncoding();
string str = e.GetString(originalAgain);

Now this doesn't work to decrypt however if des1.CreateDecryptor(); is changed to des.CreateDecryptor(); it works fine and I am unsure as to why if I am using the exact same key.

It is not throwing an exception it just isn't converting the string correctly.

+4  A: 

Unless you are using something like ECB mode, the decryptor needs the initialization vector used by the encryptor.

erickson
+3  A: 

It is because you are not setting the initialization vector (IV) the DESCryptoServiceProvider will automatically generate one for you and as you have 2 seperate instances they are going to be different.

caveman_dick