Crypto++ (CryptoPP) 是功能完整、經過大規模驗證的 C++ 密碼庫,但目錄結構龐雜(根目錄混雜源碼、專案檔、多平台支援),初學者易望而卻步。本文以 VC6 + 靜態連結為例,梳理編譯與核心 API 用法。
cryptlib.libcryptopp.dsw,建置 cryptlib 專案(Release/Debug 對應主專案)。cryptlib.lib 複製至測試專案 cryptopp/lib/。.h 複製至 cryptopp/include/,專案加入此包含路徑。Debug Multithreaded DLL 或 Release Multithreaded DLL),否則連結報錯 LNK2005。#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
#include "md5.h"
using namespace CryptoPP;
#pragma comment(lib, "cryptopp\\lib\\cryptlib.lib")
int main() {
byte msg[] = "HelloWorld!";
byte digest[16];
Weak::MD5 md5;
md5.Update(msg, 11);
md5.Final(digest);
for (int i=0; i<16; i++) printf("%02X", digest[i]);
printf("\n");
return 0;
}
#include "default.h"
#include "cryptlib.h"
#include "filters.h"
#include "modes.h"
#include "aes.h"
#include "hex.h"
using namespace CryptoPP;
int main() {
byte key[16] = {0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,
0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08};
byte iv[16] = {0x01,0x02,0x03,0x03,0x03,0x03,0x03,0x03,
0x03,0x03,0x01,0x02,0x03,0x03,0x03,0x03};
string plain = "Hello World!";
string cipher, recovered;
// CBC + ONE_AND_ZEROS_PADDING
CBC_Mode::Encryption enc(key, 16, iv);
StringSource(plain, true,
new StreamTransformationFilter(enc,
new StringSink(cipher),
BlockPaddingSchemeDef::ONE_AND_ZEROS_PADDING));
CBC_Mode::Decryption dec(key, 16, iv);
StringSource(cipher, true,
new StreamTransformationFilter(dec,
new StringSink(recovered),
BlockPaddingSchemeDef::ONE_AND_ZEROS_PADDING));
// CTR + NO_PADDING
cipher.clear(); recovered.clear();
CTR_Mode::Encryption enc2(key, 16, iv);
StringSource(plain, true,
new StreamTransformationFilter(enc2,
new StringSink(cipher),
BlockPaddingSchemeDef::NO_PADDING));
CTR_Mode::Decryption dec2(key, 16, iv);
StringSource(cipher, true,
new StreamTransformationFilter(dec2,
new StringSink(recovered),
BlockPaddingSchemeDef::NO_PADDING));
return 0;
}
SecByteBlock HexDecode(const char* hex) {
StringSource ss(hex, true, new HexDecoder);
SecByteBlock result(ss.MaxRetrievable());
ss.Get(result, result.size());
return result;
}
void AES_CTR_EncryptFile(const char* hexKey, const char* hexIV,
const char* infile, const char* outfile) {
SecByteBlock key = HexDecode(hexKey);
SecByteBlock iv = HexDecode(hexIV);
CTR_Mode::Encryption aes(key, key.size(), iv);
FileSource(infile, true,
new StreamTransformationFilter(aes, new FileSink(outfile)));
}
StringSource:字串/位元組陣列輸入源,三種建構子支援 const char*、byte*+len、std::string。FileSource/FileSink:檔案流管線。StreamTransformationFilter:串接加密轉換與輸出端,參數控制 Padding。cryptest/test.cpp:GenerateRSAKey、RSAEncryptString、RSASignFile 等。LNK2005 重複定義。<iostream.h> vs 新版 <iostream> + using namespace std;。