简体   繁体   中英

DES Encryption in C#

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.

除非您使用类似ECB模式的东西,否则解密器需要加密器使用的初始化向量。

这是因为您没有设置初始化向量(IV),DESCryptoServiceProvider将自动为您生成一个,因为您有2个单独的实例,它们将是不同的。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM