首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

C# 常用字串加密解密封裝:MD5、SHA1、DES、AES 完整實作

     編輯:更多程式設計知識

一、不可逆雜湊:MD5 / SHA1

依賴 System.Web.Security.FormsAuthentication(需引用 System.Web.dll):

public string SHA1(string source) 
    => FormsAuthentication.HashPasswordForStoringInConfigFile(source, "SHA1");

public string MD5(string source) 
    => FormsAuthentication.HashPasswordForStoringInConfigFile(source, "MD5");

注意:ASP.NET Core 已移除此 API,新專案建議改用 System.Security.Cryptography 原生實作。

二、對稱加密:DES(CBC 模式 + Base64)

private const string KEY_64 = "8chars!!"; // 必須 8 位元組
private const string IV_64  = "8chars!!";

public string DesEncrypt(string data) {
    byte[] key = Encoding.ASCII.GetBytes(KEY_64);
    byte[] iv  = Encoding.ASCII.GetBytes(IV_64);
    using (var des = new DESCryptoServiceProvider())
    using (var ms = new MemoryStream())
    using (var cs = new CryptoStream(ms, des.CreateEncryptor(key, iv), CryptoStreamMode.Write))
    using (var sw = new StreamWriter(cs)) {
        sw.Write(data);
        sw.Flush();
        cs.FlushFinalBlock();
        return Convert.ToBase64String(ms.ToArray());
    }
}

public string DesDecrypt(string data) {
    byte[] key = Encoding.ASCII.GetBytes(KEY_64);
    byte[] iv  = Encoding.ASCII.GetBytes(IV_64);
    byte[] input;
    try { input = Convert.FromBase64String(data); }
    catch { return null; }

    using (var des = new DESCryptoServiceProvider())
    using (var ms = new MemoryStream(input))
    using (var cs = new CryptoStream(ms, des.CreateDecryptor(key, iv), CryptoStreamMode.Read))
    using (var sr = new StreamReader(cs)) {
        return sr.ReadToEnd();
    }
}

三、對稱加密:AES (RijndaelManaged) - 推薦

public class AesCrypto {
    private readonly SymmetricAlgorithm _alg = new RijndaelManaged();
    private readonly string _key = "Guz(%&hj7x89H$yuBI0456FtmaT5&fvHUFCy76*h%(HilJ$lhj!y6&(*jkP87jH7";
    private readonly string _iv  = "E4ghj*Ghg7!rNIfb&95GUY86GfghUb#er57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk";

    private byte[] GetLegalKey() {
        var keyBytes = _alg.Key;
        var str = _key.Length > keyBytes.Length ? _key.Substring(0, keyBytes.Length) : _key.PadRight(keyBytes.Length, ' ');
        return Encoding.ASCII.GetBytes(str);
    }
    private byte[] GetLegalIV() {
        var ivBytes = _alg.IV;
        var str = _iv.Length > ivBytes.Length ? _iv.Substring(0, ivBytes.Length) : _iv.PadRight(ivBytes.Length, ' ');
        return Encoding.ASCII.GetBytes(str);
    }

    public string Encrypt(string plain) {
        var input = Encoding.UTF8.GetBytes(plain);
        using (var ms = new MemoryStream()) {
            _alg.Key = GetLegalKey();
            _alg.IV = GetLegalIV();
            using (var cs = new CryptoStream(ms, _alg.CreateEncryptor(), CryptoStreamMode.Write)) {
                cs.Write(input, 0, input.Length);
                cs.FlushFinalBlock();
            }
            return Convert.ToBase64String(ms.ToArray());
        }
    }

    public string Decrypt(string cipher) {
        var input = Convert.FromBase64String(cipher);
        using (var ms = new MemoryStream(input)) {
            _alg.Key = GetLegalKey();
            _alg.IV = GetLegalIV();
            using (var cs = new CryptoStream(ms, _alg.CreateDecryptor(), CryptoStreamMode.Read))
            using (var sr = new StreamReader(cs)) {
                return sr.ReadToEnd();
            }
        }
    }
}

四、MD5 變體:32 位 / 16 位十六進制輸出

public static string MD5_32(string input, string charset = "utf-8") {
    using (var md5 = MD5.Create()) {
        var bytes = md5.ComputeHash(Encoding.GetEncoding(charset).GetBytes(input));
        var sb = new StringBuilder(32);
        foreach (var b in bytes) sb.Append(b.ToString("x2"));
        return sb.ToString();
    }
}

public static string MD5_16(string input) {
    using (var md5 = MD5.Create()) {
        var bytes = md5.ComputeHash(Encoding.Default.GetBytes(input));
        return BitConverter.ToString(bytes, 4, 8).Replace("-", "");
    }
}

五、檔案級加密/解密 (DES 流式處理)

public static void EncryptFile(string inPath, string outPath, byte[] key, byte[] iv) {
    using (var fin = File.OpenRead(inPath))
    using (var fout = File.Create(outPath))
    using (var des = DES.Create())
    using (var cs = new CryptoStream(fout, des.CreateEncryptor(key, iv), CryptoStreamMode.Write)) {
        var buffer = new byte[4096];
        int read;
        while ((read = fin.Read(buffer, 0, buffer.Length)) > 0)
            cs.Write(buffer, 0, read);
    }
}

public static void DecryptFile(string inPath, string outPath, byte[] key, byte[] iv) {
    using (var fin = File.OpenRead(inPath))
    using (var fout = File.Create(outPath))
    using (var des = DES.Create())
    using (var cs = new CryptoStream(fout, des.CreateDecryptor(key, iv), CryptoStreamMode.Write)) {
        var buffer = new byte[4096];
        int read;
        while ((read = fin.Read(buffer, 0, buffer.Length)) > 0)
            cs.Write(buffer, 0, read);
    }
}

安全性提醒

  • DES 已淘汰:鑰鑰長度 56 bits,極易暴力破解。生產環境請使用 AES-256 (RijndaelManaged / Aes)。
  • 金鑰管理:避免硬編碼金鑰,應使用 DPAPI、Key Vault 或環境變數注入。
  • IV 唯一性:每次加密應生成隨機 IV,並與密文一併儲存(如預置在密文頭部)。
  • 完整性驗證:單純加密無法防範竄改,建議採用 AesGcm (AEAD) 或額外加上 HMAC。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved