CryptoPP:加解密之aes
CryptoPP是一个强大的密码库,官网是https://www.cryptopp.com/。上面有比较详细的具体例子和说明文档,不过例子程序稍显片面,无法满足所有的应用场景,把这2天研究的一些加解密算法封装一下分享出来。
AES
简单粗暴直接贴代码
// AES编码,返回的是base64编码的数据
std::string crypto::aes_encrypt(unsigned char* key, int keylen, unsigned char* iv,
std::string data)
{
std::string encrypt_str;
try {
// 初始化编码器 这里选择的mode是CBC_Mode
CryptoPP::CBC_Mode<CryptoPP::AES>::Encryption cbc_encription(key, keylen, iv);
// 设置一个流格式化 CryptoPP很好用的一个模块
CryptoPP::StreamTransformationFilter stf_encription(cbc_encription,
// 这里使加密的输出流用base64编码,如果不需要则直接传new CryptoPP::StringSink(encrypt_str)
new CryptoPP::Base64Encoder(new CryptoPP::StringSink(encrypt_str)),
// 填充模式是填充0
CryptoPP::BlockPaddingSchemeDef::ZEROS_PADDING);
// put将需要编码的数据传入
stf_encription.Put(reinterpret_cast<const unsigned char*>(data.c_str()), data.length() + 1);
stf_encription.MessageEnd();
}
catch (std::exc