C#DES加密解密的代码
时间: 2023-11-23 18:45:24 浏览: 132
以下是使用C#进行DES加密和解密的代码示例:
```csharp
using System;
using System.Security.Cryptography;
using System.Text;
public class DESExample
{
public static string Encrypt(string plainText, byte[] key, byte[] iv)
{
byte[] encrypted;
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
{
des.Key = key;
des.IV = iv;
ICryptoTransform encryptor = des.CreateEncryptor(des.Key, des.IV);
using (var memoryStream = new System.IO.MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
using (var streamWriter = new System.IO.StreamWriter(cryptoStream))
{
streamWriter.Write(plainText);
}
encrypted = memoryStream.ToArray();
}
}
}
return Convert.ToBase64String(encrypted);
}
public static string Decrypt(string cipherText, byte[] key, byte[] iv)
{
byte[] decrypted;
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
{
des.Key = key;
des.IV = iv;
ICryptoTransform decryptor = des.CreateDecryptor(des.Key, des.IV);
using (var memoryStream = new System.IO.MemoryStream(Convert.FromBase64String(cipherText)))
{
using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
using (var streamReader = new System.IO.StreamReader(cryptoStream))
{
decrypted = Encoding.UTF8.GetBytes(streamReader.ReadToEnd());
}
}
}
}
return Encoding.UTF8.GetString(decrypted);
}
}
```
使用示例:
```csharp
byte[] key = Encoding.UTF8.GetBytes("01234567");
byte[] iv = Encoding.UTF8.GetBytes("abcdefgh");
string plainText = "Hello, World!";
string encryptedText = DESExample.Encrypt(plainText, key, iv);
Console.WriteLine($"Encrypted: {encryptedText}");
string decryptedText = DESExample.Decrypt(encryptedText, key, iv);
Console.WriteLine($"Decrypted: {decryptedText}");
```
阅读全文