DES加解密字符串c#
时间: 2024-10-29 13:06:01 浏览: 14
C# des对称加密字符串实例
在C#中,Data Encryption Standard (DES)是一种对称加密算法,常用于数据的安全传输。下面是使用System.Security.Cryptography命名空间中的`DESCryptoServiceProvider`类来进行DES加解密的基本步骤:
### 加密示例:
```csharp
using System;
using System.Security.Cryptography;
public class DESExample {
private DESCryptoServiceProvider des;
public DESExample() {
des = new DESCryptoServiceProvider();
}
// 加密函数
public string EncryptString(string plainText, byte[] key, byte[] iv) {
using (MemoryStream memoryStream = new MemoryStream()) {
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, des.CreateEncryptor(key, iv), CryptoStreamMode.Write)) {
using (StreamWriter writer = new StreamWriter(cryptoStream)) {
writer.Write(plainText);
}
return Convert.ToBase64String(memoryStream.ToArray());
}
}
}
// 示例调用
static void Main() {
string key = Encoding.UTF8.GetBytes("your_secret_key_128_chars");
byte[] iv = Encoding.UTF8.GetBytes("your_initialization_vector");
string plaintext = "Your message to encrypt";
DESExample desEx = new DESExample();
string ciphertext = desEx.EncryptString(plaintext, key, iv);
Console.WriteLine($"Encrypted: {ciphertext}");
}
}
```
### 解密示例:
```csharp
// 解密函数
public string DecryptString(string cipherText, byte[] key, byte[] iv) {
byte[] decodedBytes = Convert.FromBase64String(cipherText);
using (MemoryStream memoryStream = new MemoryStream(decodedBytes)) {
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, des.CreateDecryptor(key, iv), CryptoStreamMode.Read)) {
using (StreamReader reader = new StreamReader(cryptoStream)) {
return reader.ReadToEnd();
}
}
}
}
// 示例调用
string decryptedText = desEx.DecryptString(ciphertext, key, iv);
Console.WriteLine($"Decrypted: {decryptedText}");
```
**注意事项:**
1. `key`应该是一个16字节(128位)的密钥,通常你需要将其安全存储并仅在需要的时候生成。
2. `iv`(初始化向量)也是一个8字节(64位)的值,每次加密都需要一个唯一的IV,一般会作为明文的一部分提供。
阅读全文