資料加密是系統安全的基礎環節。本文提供一個可直接落地的 Encryption 靜態類別,採用 DES 對稱加密演算法,支援自訂金鑰(預設 8 字元),並示範如何在專案中快速整合。
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
namespace Encryption.App_Code
{
///
/// DES 加密/解密工具類
///
public static class Encryption
{
// 預設金鑰(必須 8 字元)
private static string DefaultKey => "hongye10";
// 固定 IV(初始化向量)
private static readonly byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
///
/// 加密(使用預設金鑰)
///
public static string DesEncrypt(string inputString)
=> DesEncrypt(inputString, DefaultKey);
///
/// 解密(使用預設金鑰)
///
public static string DesDecrypt(string inputString)
=> DesDecrypt(inputString, DefaultKey);
///
/// 加密字串
///
/// 明文
/// 金鑰(取前 8 字元)
/// Base64 編碼的密文,失敗回傳 null
public static string DesEncrypt(string inputString, string encryptKey)
{
try
{
byte[] keyBytes = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
using var des = new DESCryptoServiceProvider();
byte[] inputBytes = Encoding.UTF8.GetBytes(inputString);
using var ms = new MemoryStream();
using var cs = new CryptoStream(ms, des.CreateEncryptor(keyBytes, IV), CryptoStreamMode.Write);
cs.Write(inputBytes, 0, inputBytes.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
catch
{
return null;
}
}
///
/// 解密字串
///
/// Base64 密文
/// 金鑰(取前 8 字元)
/// 明文,失敗回傳 null
public static string DesDecrypt(string inputString, string decryptKey)
{
try
{
byte[] keyBytes = Encoding.UTF8.GetBytes(decryptKey.Substring(0, 8));
using var des = new DESCryptoServiceProvider();
byte[] inputBytes = Convert.FromBase64String(inputString);
using var ms = new MemoryStream();
using var cs = new CryptoStream(ms, des.CreateDecryptor(keyBytes, IV), CryptoStreamMode.Write);
cs.Write(inputBytes, 0, inputBytes.Length);
cs.FlushFinalBlock();
return Encoding.UTF8.GetString(ms.ToArray());
}
catch
{
return null;
}
}
}
}
string original = "敏感資料 12345";
string encrypted = Encryption.DesEncrypt(original); // 加密
string decrypted = Encryption.DesDecrypt(encrypted); // 解密
Console.WriteLine($"原文:{original}");
Console.WriteLine($"密文:{encrypted}");
Console.WriteLine($"解密:{decrypted}");
Substring(0,8);若金鑰不足 8 字元會拋出例外,建議呼叫端自行驗證。null,正式環境建議記錄日誌或拋出自訂例外。AesCryptoServiceProvider 實作。// 僅示範關鍵行變更
using var aes = new AesCryptoServiceProvider { KeySize = 128, BlockSize = 128 };
aes.Key = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 16)); // AES-128 需 16 字元
aes.IV = IV; // 或隨機產生
// 其餘 CryptoStream 流程相同