凱撒密碼是最古老的替換加密演算法。本文實作一個變體:**加密後字串首字元 = 原字串尾字元,其餘各字元 = 原字串前一字元的 ASCII/Unicode 值 + 3**。雖極不安全,但適合理解字元編碼操作、字串陣列操作、模運算等基礎概念。
輸入: w e l c o m e (索引 0~6)
輸出: e z h o f r p
↑ ↑ ↑ ↑ ↑ ↑ ↑
原[6] 原[0]+3 原[1]+3 原[2]+3 原[3]+3 原[4]+3 原[5]+3
using System;
public class ShiftCipher
{
///
/// 移位加密:首字元取原尾字元,其餘各字元 = 原前一字元 + 3
///
public static string Encrypt(string input)
{
if (string.IsNullOrEmpty(input)) return input;
if (input.Length == 1) return new string(new char[] { (char)(input[0] + 3) });
char[] src = input.ToCharArray();
char[] dst = new char[src.Length];
// 首字元 = 原尾字元
dst[0] = src[src.Length - 1];
// 其餘字元 = 原前一字元 + 3
for (int i = 1; i < src.Length; i++)
{
int val = src[i - 1] + 3;
dst[i] = (char)val;
}
return new string(dst);
}
///
/// 解密:逆向操作
///
public static string Decrypt(string input)
{
if (string.IsNullOrEmpty(input)) return input;
if (input.Length == 1) return new string(new char[] { (char)(input[0] - 3) });
char[] src = input.ToCharArray();
char[] dst = new char[src.Length];
// 原尾字元 = 加密首字元
dst[dst.Length - 1] = src[0];
// 原前一字元 = 加密字元 - 3
for (int i = 1; i < src.Length; i++)
{
int val = src[i] - 3;
dst[i - 1] = (char)val;
}
return new string(dst);
}
public static void Main()
{
Console.Write("請輸入要加密的字串:");
string input = Console.ReadLine();
string encrypted = Encrypt(input);
string decrypted = Decrypt(encrypted);
Console.WriteLine($"原文: {input}");
Console.WriteLine($"密文: {encrypted}");
Console.WriteLine($"解密: {decrypted}");
Console.WriteLine($"驗證: {(input == decrypted ? "通過" : "失敗")}");
}
}
請輸入要加密的字串:welcome
原文: welcome
密文: ezhofrp
解密: welcome
驗證: 通過
ToCharArray():字串轉可變字元陣列(char)(val):整數轉字元(隱式截斷超出範圍值)new string(char[]):陣列建構字串| 弱點 | 說明 |
|---|---|
| 金鑰空間極小 | 固定位移 3,無金鑰參數,破解成本 O(1) |
| 頻率分析 | 單表替換密碼,字母頻率分布不變,極易破解 |
| 已知明文攻擊 | 一組明密文對即可推導完整映射規則 |
| 無完整性保護 | 任意修改密文解密後僅局部亂碼,無法偵測竄改 |
| 字元溢位未處理 | char + 3 超過 char.MaxValue 會環繞,解密失敗 |
public static string EncryptImproved(string input, int shift)
{
if (string.IsNullOrEmpty(input)) return input;
shift = shift % 65536; // char 範圍 0~65535
char[] src = input.ToCharArray();
char[] dst = new char[src.Length];
dst[0] = src[^1];
for (int i = 1; i < src.Length; i++)
dst[i] = (char)((src[i - 1] + shift) % 65536);
return new string(dst);
}
public static string DecryptImproved(string input, int shift)
{
if (string.IsNullOrEmpty(input)) return input;
shift = shift % 65536;
char[] src = input.ToCharArray();
char[] dst = new char[src.Length];
dst[^1] = src[0];
for (int i = 1; i < src.Length; i++)
dst[i - 1] = (char)((src[i] - shift + 65536) % 65536);
return new string(dst);
}
Aes.GenerateKey() + Aes.CreateEncryptor()(GCM 模式提供認證加密)RSA / ECDsa 簽名與金鑰交換Rfc2898DeriveBytes (PBKDF2) / Argon2 將密碼轉金鑰Microsoft.AspNetCore.DataProtection、libsodium-net、NaCl移位密碼是理解「字元編碼位移」、「字串陣列索引操作」、「可逆演算法設計」的優秀教學範例。**切記:任何自行設計的加密演算法在生產環境皆為零安全性**,請務必使用經過密碼學專家審計、標準化的加密庫與演算法。