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());
}
}
// 編碼
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);
}
Aes (GCM 模式) / ChaCha20Poly1305RSA (OAEP) / ECDH + AESSystem.Security.Cryptography.ProtectedData (DPAPI)、DataProtectionProvider (ASP.NET Core Data Protection)。PBKDF2、Argon2、BCrypt、SCrypt (推薦 BCrypt.Net-Next 套件)。| 誤區 | 正確觀念 |
|---|---|
| Base64 能加密密碼 | Base64 公開可逆,等同明文 |
| 自訂演算法較安全 | 自訂密碼學極易破解,務必用經驗證標準庫 |
| 同一組金鑰長期不換 | 需定期輪換金鑰,採用金鑰管理系統 (KMS、Key Vault) |
| ECB 模式足夠 | ECB 不安全 (相同明文產生相同密文),必須用 CBC/GCM/CCM 等模式 |