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

AES 加密 C++ 調用 Crypto++ 庫完整示例

     編輯:關於C++

AES 基礎知識

  • 高級加密標準(AES),分組長度 128 位(16 字節)。
  • 密鑰長度:128/192/256 位。
  • 工作模式:ECB(不需 IV)、CBC、CFB、OFB、CTR(需 IV)。
  • Crypto++ 是成熟的 C++ 加密庫,支持上述所有模式。

CBC 模式加解密流程

  1. 生成/約定 Key (16/24/32 字節) 和 IV (16 字節)。
  2. 加密:CBC_Mode::Encryption + StreamTransformationFilter 處理填充。
  3. 輸出通常轉為十六進制字符串便於存儲/傳輸。
  4. 解密:十六進制轉回二進制,CBC_Mode::Decryption 反向處理。

完整代碼:文件加密與解密

加密程序

#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
using namespace CryptoPP;

byte key[AES::DEFAULT_KEYLENGTH], iv[AES::BLOCKSIZE];

void initKeyIV() {
    memset(key, 0, AES::DEFAULT_KEYLENGTH);
    memset(iv, 0, AES::BLOCKSIZE);
    // 實際應用中應從安全隨機源生成或密鑰派生函數獲取
}

string encrypt(const string& plain) {
    string cipher;
    CBC_Mode::Encryption enc(key, sizeof(key), iv);
    StringSource(plain, true,
        new StreamTransformationFilter(enc,
            new StringSink(cipher)
        )
    );
    string hex;
    StringSource(cipher, true, new HexEncoder(new StringSink(hex)));
    return hex;
}

int main() {
    initKeyIV();
    string plain = "敏感數據內容";
    string cipherHex = encrypt(plain);
    ofstream out("cipher.dat", ios::binary);
    out.write(cipherHex.c_str(), cipherHex.size());
    cout << "加密完成,輸出十六進制長度: " << cipherHex.size() << endl;
    return 0;
}

解密程序

string decrypt(const string& cipherHex) {
    string cipher;
    StringSource(cipherHex, true, new HexDecoder(new StringSink(cipher)));
    string recovered;
    CBC_Mode::Decryption dec(key, sizeof(key), iv);
    StringSource(cipher, true,
        new StreamTransformationFilter(dec,
            new StringSink(recovered)
        )
    );
    return recovered;
}

int main() {
    initKeyIV();
    ifstream in("cipher.dat");
    string hex((istreambuf_iterator(in)), istreambuf_iterator());
    string plain = decrypt(hex);
    cout << "解密結果: " << plain << endl;
    return 0;
}

編譯與鏈接

sudo apt-get install libcrypto++-dev
g++ encrypt.cpp -o encrypt -lcryptopp
g++ decrypt.cpp -o decrypt -lcryptopp

安全提示

  • 切勿硬編碼 Key/IV,應使用 PBKDF2、Argon2 等從密碼派生,或密鑰管理系統。
  • IV 必須隨機且每次加密唯一,CBC 模式下 IV 不需保密但不可重複使用。
  • 生產環境建議使用認證加密(GCM/CCM)防止篡改。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved