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

C# 字串加密與解密:Base64 自訂實作與內建 API 最佳實務

     編輯:關於C語言

自訂 Base64 實作 (教學用)

public static class CustomBase64
{
    private const string Chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=";

    public static string Encrypt(string plain)
    {
        byte[] bytes = Encoding.Default.GetBytes(plain);
        int groups = (bytes.Length + 2) / 3;
        StringBuilder sb = new StringBuilder(groups * 4);

        for (int i = 0; i < groups; i++)
        {
            byte b1 = i * 3 < bytes.Length ? bytes[i * 3] : (byte)0;
            byte b2 = i * 3 + 1 < bytes.Length ? bytes[i * 3 + 1] : (byte)0;
            byte b3 = i * 3 + 2 < bytes.Length ? bytes[i * 3 + 2] : (byte)0;

            int[] idx = new int[4];
            idx[0] = b1 >> 2;
            idx[1] = ((b1 & 0x03) << 4) | (b2 >> 4);
            idx[2] = (i * 3 + 1 < bytes.Length) ? ((b2 & 0x0F) << 2) | (b3 >> 6) : 64;
            idx[3] = (i * 3 + 2 < bytes.Length) ? (b3 & 0x3F) : 64;

            foreach (int id in idx) sb.Append(Chars[id]);
        }
        return sb.ToString();
    }

    public static string Decrypt(string cipher)
    {
        if (cipher.Length % 4 != 0)
            throw new ArgumentException("Invalid Base64 length");

        List output = new List();
        for (int i = 0; i < cipher.Length; i += 4)
        {
            int i1 = Chars.IndexOf(cipher[i]);
            int i2 = Chars.IndexOf(cipher[i + 1]);
            int i3 = Chars.IndexOf(cipher[i + 2]);
            int i4 = Chars.IndexOf(cipher[i + 3]);
            if (i1 < 0 || i2 < 0 || i3 < 0 || i4 < 0)
                throw new ArgumentException("Invalid Base64 char");

            output.Add((byte)((i1 << 2) | (i2 >> 4)));
            if (i3 != 64) output.Add((byte)((i2 << 4) | (i3 >> 2)));
            if (i4 != 64) output.Add((byte)((i3 << 6) | i4));
        }
        return Encoding.Default.GetString(output.ToArray());
    }
}

生產環境:直接使用內建 API

// 編碼
string encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes("敏感資料"));

// 解碼
string decoded = Encoding.UTF8.GetString(Convert.FromBase64String(encoded));

優點:標準相容 (RFC 4648)、效能最佳化、支援 Base64Url 變體 (Convert.ToBase64String(bytes).TrimEnd('=').Replace('+','-').Replace('/','_'))。

檔案加密/解密流程

public static void EncryptFile(string inputPath, string outputPath)
{
    byte[] content = File.ReadAllBytes(inputPath);
    string base64 = Convert.ToBase64String(content);
    File.WriteAllText(outputPath, base64, Encoding.UTF8);
}

public static void DecryptFile(string inputPath, string outputPath)
{
    string base64 = File.ReadAllText(inputPath, Encoding.UTF8);
    byte[] content = Convert.FromBase64String(base64);
    File.WriteAllBytes(outputPath, content);
}

⚠️ 重要安全提醒

  • Base64 是編碼,非加密:無金鑰、可直接還原,不可用於保護機密資料。
  • 真正加密請使用:
    - 對稱加密:Aes (GCM 模式) / ChaCha20Poly1305
    - 非對稱加密:RSA (OAEP) / ECDH + AES
    - 高階 API:System.Security.Cryptography.ProtectedData (DPAPI)、DataProtectionProvider (ASP.NET Core Data Protection)。
  • 密碼儲存**絕不可**使用可逆加密,必須用 鹽值雜湊:PBKDF2、Argon2、BCrypt、SCrypt (推薦 BCrypt.Net-Next 套件)。

常見誤區對照

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
誤區正確觀念
Base64 能加密密碼Base64 公開可逆,等同明文
自訂演算法較安全自訂密碼學極易破解,務必用經驗證標準庫
同一組金鑰長期不換需定期輪換金鑰,採用金鑰管理系統 (KMS、Key Vault)
ECB 模式足夠ECB 不安全 (相同明文產生相同密文),必須用 CBC/GCM/CCM 等模式