AES 基礎知識
- 高級加密標準(AES),分組長度 128 位(16 字節)。
- 密鑰長度:128/192/256 位。
- 工作模式:ECB(不需 IV)、CBC、CFB、OFB、CTR(需 IV)。
- Crypto++ 是成熟的 C++ 加密庫,支持上述所有模式。
CBC 模式加解密流程
- 生成/約定 Key (16/24/32 字節) 和 IV (16 字節)。
- 加密:
CBC_Mode::Encryption + StreamTransformationFilter 處理填充。
- 輸出通常轉為十六進制字符串便於存儲/傳輸。
- 解密:十六進制轉回二進制,
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)防止篡改。