萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C# DES 加密解密完整實現:ECB/CBC 模式、Key/IV 管理、Base64 編碼

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);  // 輸出原文

關鍵參數說明

參數值說明
AlgorithmDES對稱分組加密, 塊大小 64 位
ModeCBC (Cipher Block Chaining)需 IV, 比 ECB 安全
PaddingPKCS7 (默認)自動填充至 8 字節倍數
Key Size64 位 (含 8 位校驗, 有效 56 位)KEY_64 必須 8 字符
IV Size64 位IV_64 必須 8 字符
EncodingUTF-8 (明文) / Base64 (密文)跨平台安全傳輸

安全建議

  • 棄用 DES 用於新系統:改用 AES (Rijndael),密鑰 128/192/256 位,性能更好、安全性高得多。
  • Key/IV 切勿硬編碼:使用配置文件、環境變量、Azure Key Vault、HashiCorp Vault 等密鑰管理方案。
  • 每次加密生成隨機 IV:將 IV 與密文一起存儲 (如 IV + CipherText),解密時分離,防止相同明文產生相同密文。
  • 認證加密 (AEAD):AES-GCM、ChaCha20-Poly1305 同時保證機密性與完整性。

遷移到 AES 示例

using (var aes = Aes.Create())
{
    aes.KeySize = 256;
    aes.GenerateKey();
    aes.GenerateIV();
    // 其餘流程同 DES, 只需替換 Provider
}

理解 DES 內部機制有助於維護舊系統,但新項目請直接上 AES-GCM。

copyright © 萬盛學電腦網 all rights reserved