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

C++ 實現簡化版恩格瑪加密機

     編輯:關於C++

原理簡介

恩格瑪機是二戰德軍使用的加密設備,核心特性:**自反性** —— 同一初始設置下,加密與解密操作完全相同。即 `Enigma(Enigma(plain)) = plain`。

簡化模型(無插板、固定反射器):

  • 轉子:每個轉子是一個置換(本例用凱撒位移模擬)。輸入字符經所有轉子依次位移。
  • 反射器:將字符映射為另一字符,且滿足 `reflect(reflect(c)) = c`。本例用:偶數字符 +1,奇數字符 -1(即兩兩配對:a↔b, c↔d...)。
  • 回程:經反射器後,按逆序通過轉子,每個轉子做逆位移。
  • 轉子轉動:每加密一字符,最右轉子進位;滿 26 進位到下一轉子(如里程表)。

完整代碼


#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

擴展方向

  • 加入**插板**:加密前後做固定字符對換換。
  • 真實轉子接線:用 26 長度數組表示任意置換,而非單純位移。
  • 多反射器選擇、轉子順序可配置。

總結

恩格瑪機的核心是「可變置換 + 自反性」。本簡化版用凱撒位移模擬轉子、簡單配對模擬反射器,完整演示了加密/解密同一流程。理解此模型有助於掌握經典密碼學機械化加密原理。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved