Crypto++ 是功能最全面的 C++ 加密庫,但原始碼龐大(靜態庫高達 34 MB),導出最小化二進位需額外裁剪。本文提供一個可直接編譯的極簡範例,示範 RSA 金鑰對生成、字串加密、解密、簽名/驗簽 的核心流程,適合快速整合至專案。
| 功能 | Crypto++ 類別 | 備註 |
|---|---|---|
| 私鑰解密/簽名 | RSAES_OAEP_SHA_Decryptor / RSASS_PKCS1v15_SHA_Signer | OAEP 填充 + SHA-1 |
| 公鑰加密/驗簽 | RSAES_OAEP_SHA_Encryptor / RSASS_PKCS1v15_SHA_Verifier | 對應之公鑰操作 |
| 編碼/解碼 | HexEncoder / HexDecoder | 二進位 ↔ 十六進位字串 |
| 檔案 I/O | FileSource / FileSink | 管道式串流處理 |
| 隨機數源 | RandomPool / AutoSeededRandomPool | 現代建議改用後者 |
#include <cryptopp/rsa.h>
#include <cryptopp/osrng.h>
#include <cryptopp/hex.h>
#include <cryptopp/files.h>
#include <iostream>, <string>
using namespace CryptoPP;
void GenKeys(const char* priFile, const char* pubFile, unsigned int bits=2048) {
AutoSeededRandomPool rng;
InvertibleRSAFunction params;
params.GenerateRandomWithKeySize(rng, bits);
params.DEREncode(FileSink(priFile).Ref());
RSAFunction pub(params);
pub.DEREncode(FileSink(pubFile).Ref());
}
std::string Encrypt(const char* pubFile, const std::string& plain) {
FileSource fs(pubFile, true, new HexDecoder);
RSAES_OAEP_SHA_Encryptor encryptor(fs);
AutoSeededRandomPool rng;
std::string cipher;
StringSource(plain, true,
new PK_EncryptorFilter(rng, encryptor,
new HexEncoder(new StringSink(cipher))));
return cipher;
}
std::string Decrypt(const char* priFile, const std::string& cipher) {
FileSource fs(priFile, true, new HexDecoder);
RSAES_OAEP_SHA_Decryptor decryptor(fs);
AutoSeededRandomPool rng;
std::string plain;
StringSource(cipher, true,
new HexDecoder(new PK_DecryptorFilter(rng, decryptor,
new StringSink(plain))));
return plain;
}
int main() {
GenKeys("pri.der", "pub.der", 2048);
std::string msg = "Hello Crypto++ RSA!";
std::string enc = Encrypt("pub.der", msg);
std::string dec = Decrypt("pri.der", enc);
std::cout << "Original: " << msg << "\nEncrypted: " << enc << "\nDecrypted: " << dec << std::endl;
return 0;
}
rsa.cpp、oaep.cpp、sha.cpp、hex.cpp、files.cpp 等核心檔,可將靜態庫壓縮至 2~3 MB。「Crypto++ 功能強大但學習曲線陡峭;掌握『管道式』串流設計(Source → Filter → Sink)是駕馭它的關鍵。」