cryptoPP的使用

website

编译

下载源码后目录里面有 .sln 文件。

AES加解密

CTR is used if you want good parallelization (ie. speed), instead of CBC/OFB/CFB.

#include <cryptopp/osrng.h>
#include <cryptopp/cryptlib.h>
#include <cryptopp/aes.h>
#include <cryptopp/filters.h>
#include <cryptopp/files.h>
#include <cryptopp/modes.h>
#include <cryptopp/hex.h>
using namespace CryptoPP;

#ifdef _DEBUG
#pragma comment(lib,"cryptopp/vs2015/debug/cryptlib.lib")
#else
#pragma comment(lib,"cryptopp/vs2015/release/cryptlib.lib")
#endif

unsigned char key[AES::DEFAULT_KEYLENGTH];
unsigned char iv[AES::BLOCKSIZE];

memset(key, 0x00, sizeof(key));
memset(iv, 0x00, sizeof(iv));

AutoSeededRandomPool rnd;
rnd.GenerateBlock(key, AES::DEFAULT_KEYLENGTH);

// Generate a random IV
rnd.GenerateBlock(iv, AES::BLOCKSIZE);

string strKey, strIv;
vector<char> vBuf;
byte2StrA(key, AES::DEFAULT_KEYLENGTH, vBuf);
strKey = &vBuf[0];

byte2StrA(iv, AES::BLOCKSIZE, vBuf);
strIv = &vBuf[0];

// HexEncoder 返回16进制数据,没有这个返回字符串
CTR_Mode<AES>::Encryption enc;
enc.SetKeyWithIV(key, sizeof(key), iv);
string encText;
StreamTransformationFilter encFilter(enc, new HexEncoder(new StringSink(encText)));

string strPlain("Attack at dawn!");
//encryption
encFilter.Put((const unsigned char*)strPlain.c_str(), strPlain.size());
encFilter.MessageEnd();

// decryption
CTR_Mode<AES>::Decryption dec;
dec.SetKeyWithIV(key, sizeof(key), iv);

// conversion filter for dec
string decText;
StreamTransformationFilter decFilter(dec, new HexEncoder(new StringSink(decText)));
decFilter.Put((const unsigned char*)encText.c_str(), encText.size());
decFilter.MessageEnd();