恩格瑪機是二戰德軍使用的加密設備,核心特性:**自反性** —— 同一初始設置下,加密與解密操作完全相同。即 `Enigma(Enigma(plain)) = plain`。
簡化模型(無插板、固定反射器):
#include
#include
using namespace std;
string Enigma(string input) {
int rotors[6] = {24, 2, 5, 4, 10, 23}; // 6 個轉子初始位移
const int N = 6;
string output;
for (char ch : input) {
if (ch == ' ') { output += ' '; continue; }
int code = ch - 'a';
// 正向通過轉子
for (int i = 0; i < N; ++i) code = (code + rotors[i]) % 26;
// 反射器
if (code % 2 == 0) code++; else code--;
// 逆向通過轉子
for (int i = N-1; i >= 0; --i) {
code = (code - rotors[i]) % 26;
if (code < 0) code += 26;
}
// 轉子進位
rotors[0]++;
for (int i = 0; i < N-1; ++i)
if (rotors[i] >= 26) { rotors[i] = 0; rotors[i+1]++; }
rotors[N-1] %= 26;
output += char(code + 'a');
}
return output;
}
int main() {
string text = "hey hey helloworld";
string cipher = Enigma(text);
cout << "密文: " << cipher << endl;
cout << "明文: " << Enigma(cipher) << endl; // 自反性驗證
return 0;
}
密文: ... (某亂碼) 明文: hey hey helloworld
恩格瑪機的核心是「可變置換 + 自反性」。本簡化版用凱撒位移模擬轉子、簡單配對模擬反射器,完整演示了加密/解密同一流程。理解此模型有助於掌握經典密碼學機械化加密原理。