首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

AES 對稱加密與單表替換密碼 C++ 實現資源匯總

     編輯:程式設計綜合問答

需求場景

VS2015 環境,需在一天內完成:
1. AES 加密解密(對稱加密)
2. 單表替換密碼(古典密碼學)
要求代碼簡單易懂,適合初學者。

推薦現成資源(含源碼可直接編譯)

AES 加密算法 C++ 實現

  • CSDN 下載:AES加密算法(C++實現,附源碼)
    特點:標準 Rijndael 實現,支持 128/192/256 位密鑰,ECB/CBC 模式,含測試主程序。
  • GitHub 開源庫:tiny-AES-c (C 實現,C++ 可直接調用)
    特點:單文件、無依賴、MIT 許可、極適合嵌入項目。

單表替換密碼 C++ 實現

極簡自實現參考(教學用)

AES-128-ECB 最小實現(僅演示原理,生產請用成熟庫)

#include 
#include 
#include 

void aes128_ecb_encrypt(const unsigned char* key, const unsigned char* in, unsigned char* out) {
    AES_KEY enc_key;
    AES_set_encrypt_key(key, 128, &enc_key);
    AES_encrypt(in, out, &enc_key);
}

void aes128_ecb_decrypt(const unsigned char* key, const unsigned char* in, unsigned char* out) {
    AES_KEY dec_key;
    AES_set_decrypt_key(key, 128, &dec_key);
    AES_decrypt(in, out, &dec_key);
}

int main() {
    unsigned char key[16] = "0123456789abcdef";
    unsigned char plain[16] = "HelloAESWorld!!!";
    unsigned char cipher[16], decrypted[16];
    
    aes128_ecb_encrypt(key, plain, cipher);
    aes128_ecb_decrypt(key, cipher, decrypted);
    
    printf("Plain:  %s\n", plain);
    printf("Cipher: ");
    for(int i=0;i<16;i++) printf("%02x", cipher[i]); puts("");
    printf("Decryp: %s\n", decrypted);
    return 0;
}

編譯:`g++ aes_demo.cpp -lcrypto -o aes_demo` (需安裝 OpenSSL 開發包)

單表替換密碼核心邏輯

#include 
#include 
#include 
#include 

std::string generate_key() {
    std::string key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    std::random_device rd;
    std::mt19937 g(rd());
    std::shuffle(key.begin(), key.end(), g);
    return key; // 如 "QWERTYUIOPASDFGHJKLZXCVBNM"
}

std::string encrypt_substitution(const std::string& plain, const std::string& key) {
    std::string cipher;
    for (char c : plain) {
        if (c >= 'A' && c <= 'Z') cipher += key[c - 'A'];
        else if (c >= 'a' && c <= 'z') cipher += std::tolower(key[c - 'a']);
        else cipher += c;
    }
    return cipher;
}

std::string decrypt_substitution(const std::string& cipher, const std::string& key) {
    std::string plain;
    for (char c : cipher) {
        if (c >= 'A' && c <= 'Z') {
            size_t pos = key.find(c);
            if (pos != std::string::npos) plain += 'A' + pos;
            else plain += c;
        } else if (c >= 'a' && c <= 'z') {
            size_t pos = key.find(std::toupper(c));
            if (pos != std::string::npos) plain += 'a' + pos;
            else plain += c;
        } else plain += c;
    }
    return plain;
}

工程化建議

  1. **生產環境禁用 ECB 模式**,必須用 CBC/GCM/CCM 等帶 IV/Nonce 的模式。
  2. 密鑰管理:使用 PBKDF2/Argon2 從密碼派生密鑰,或 KMS 托管。
  3. 單表替換屬**古典密碼**,極不安全(頻率分析可破),僅供教學/趣味,切勿用於真實數據保護。
  4. 推薦直接集成 OpenSSL (EVP API) 或 libsodium,而非自寫 AES。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved