C#来一段DES加解密代码
时间: 2024-11-27 19:14:04 浏览: 4
在C#中,你可以使用System.Security.Cryptography命名空间下的`DESCryptoServiceProvider`类来进行DES(Data Encryption Standard)加密和解密操作。这里是一个简单的示例:
```csharp
using System;
using System.IO;
using System.Security.Cryptography;
// 加密函数
public static string DES_encrypt(string plainText, string key)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] salt = des.GenerateSalt(8); // DES盐值长度通常为8字节
using (MemoryStream ms = new MemoryStream())
{
using (RijndaelManaged aes = new RijndaelManaged())
{
aes.Key = Encoding.ASCII.GetBytes(key);
aes.IV = salt;
aes.Mode = CipherMode.CBC; // 使用CBC模式
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
ms.Write(salt, 0, salt.Length);
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter sw = new StreamWriter(cs))
{
sw.Write(plainText);
}
}
return Convert.ToBase64String(ms.ToArray());
}
}
}
// 解密函数
public static string DES_decrypt(string encryptedText, string key)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] encryptedBytes = Convert.FromBase64String(encryptedText);
byte[] salt = new byte[8];
Array.Copy(encryptedBytes, salt, 8); // 提取盐值
using (MemoryStream ms = new MemoryStream())
{
ms.Write(salt, 0, salt.Length);
ms.Write(encryptedBytes, 8, encryptedBytes.Length - 8);
using (RijndaelManaged aes = new RijndaelManaged())
{
aes.Key = Encoding.ASCII.GetBytes(key);
aes.IV = salt;
aes.Mode = CipherMode.CBC;
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
using (StreamReader sr = new StreamReader(cs))
{
return sr.ReadToEnd();
}
}
}
}
}
```
请注意,这个例子中使用的是Rijndael而不是DES,因为DES的安全强度已经不足以满足现代需求。上述代码假设输入的key是ASCII编码的字符串。
阅读全文