DES (Data Encryption Standard) 是經典對稱加密算法,雖密鑰長度僅 56 位 (有效) 已不推薦用於高安全場景,但在老系統對接、低敏感度數據加密中仍廣泛使用。本文提供生產級 C# 封裝類,含加密、解密、異常處理、編碼轉換。
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace Vavic.Security
{
public static class DesCryptography
{
// 固定 Key/IV (生產環境應從配置讀取、密鑰管理系統獲取)
private const string KEY_64 = "VavicApp"; // 8 字節 = 64 位
private const string IV_64 = "VavicApp"; // 8 字節 = 64 位
private static byte[] KeyBytes => Encoding.ASCII.GetBytes(KEY_64);
private static byte[] IVBytes => Encoding.ASCII.GetBytes(IV_64);
/// DES 加密 (CBC 模式, PKCS7 填充), 返回 Base64 字符串
public static string Encrypt(string plainText)
{
if (string.IsNullOrEmpty(plainText))
throw new ArgumentException("明文不能為空");
using (var des = new DESCryptoServiceProvider())
using (var ms = new MemoryStream())
using (var cs = new CryptoStream(ms, des.CreateEncryptor(KeyBytes, IVBytes), CryptoStreamMode.Write))
using (var sw = new StreamWriter(cs, Encoding.UTF8))
{
sw.Write(plainText);
sw.Flush();
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
}
/// DES 解密, 輸入 Base64 字符串, 返回明文
public static string Decrypt(string cipherText)
{
if (string.IsNullOrEmpty(cipherText))
throw new ArgumentException("密文不能為空");
byte[] cipherBytes;
try { cipherBytes = Convert.FromBase64String(cipherText); }
catch { throw new FormatException("輸入非合法 Base64 字符串"); }
using (var des = new DESCryptoServiceProvider())
using (var ms = new MemoryStream(cipherBytes))
using (var cs = new CryptoStream(ms, des.CreateDecryptor(KeyBytes, IVBytes), CryptoStreamMode.Read))
using (var sr = new StreamReader(cs, Encoding.UTF8))
{
return sr.ReadToEnd();
}
}
}
}
string original = "敏感數據: 用戶密碼、身份證號";
string encrypted = DesCryptography.Encrypt(original);
Console.WriteLine("加密: " + encrypted); // 輸出 Base64 字符串
string decrypted = DesCryptography.Decrypt(encrypted);
Console.WriteLine("解密: " + decrypted); // 輸出原文
| 參數 | 值 | 說明 |
|---|---|---|
| Algorithm | DES | 對稱分組加密, 塊大小 64 位 |
| Mode | CBC (Cipher Block Chaining) | 需 IV, 比 ECB 安全 |
| Padding | PKCS7 (默認) | 自動填充至 8 字節倍數 |
| Key Size | 64 位 (含 8 位校驗, 有效 56 位) | KEY_64 必須 8 字符 |
| IV Size | 64 位 | IV_64 必須 8 字符 |
| Encoding | UTF-8 (明文) / Base64 (密文) | 跨平台安全傳輸 |
using (var aes = Aes.Create())
{
aes.KeySize = 256;
aes.GenerateKey();
aes.GenerateIV();
// 其餘流程同 DES, 只需替換 Provider
}
理解 DES 內部機制有助於維護舊系統,但新項目請直接上 AES-GCM。