Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DES Encryption in C#

Tags:

c#

encryption

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.

like image 617
Ted Smith Avatar asked Sep 15 '26 08:09

Ted Smith


2 Answers

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

like image 83
erickson Avatar answered Sep 17 '26 21:09

erickson


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.

like image 43
caveman_dick Avatar answered Sep 17 '26 20:09

caveman_dick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!