Crypto++ AES加密和解密
2023-11-18 20:43:50 281
安装
- 源码下载 https://cryptopp.com/#download
- 用visual studio打开项目
cryptlib
项目属性中配置Debug/x64
,C/C++
>代码生成
中 配置运行库为MDd
, 要保持和引用项目一致- 生成
- 目录
x64\Output\Debug\cryptlib.lib
下就是对应的库了
使用
- visual studio创建一个简单项目, 运行库同样
MDd
- 配置项目属性
C/C++
>常规
>附加包含目录
, 填cryptopp的源码路径 链接器
>输入
>附加依赖项
填库文件全路径
示例
#include <iostream>
#include <string>
#include <aes.h>
#include <filters.h>
#include <modes.h>
#include <hex.h>
using namespace std;
using namespace CryptoPP;
int main()
{
string plaintext = "Hello, Crypto++";
string key = "1234567890123456";
cout << "明文:" << plaintext << endl;
byte iv[AES::BLOCKSIZE];
memset(iv, '0', AES::BLOCKSIZE);
CBC_Mode<AES>::Encryption encryption((byte*)key.c_str(), key.length(), iv);
string ciphertext;
StringSource(plaintext, true, new StreamTransformationFilter(encryption, new CryptoPP::HexEncoder(new CryptoPP::StringSink(ciphertext), false)));
cout << "密文:" << ciphertext << endl;
std::string hexDecodedCipherText;
CryptoPP::StringSource(ciphertext, true,
new CryptoPP::HexDecoder(
new CryptoPP::StringSink(hexDecodedCipherText)
)
);
CBC_Mode<AES>::Decryption decryption((byte *)key.c_str(), key.length(), iv);
string decryptedtext;
StringSource(hexDecodedCipherText, true, new StreamTransformationFilter(decryption, new StringSink(decryptedtext)));
cout << "解密后的明文:" << decryptedtext << endl;
return 0;
}
输出
明文:Hello, Crypto++
密文:5870292e8773d7d61055e4062e41c5a6
解密后的明文:Hello, Crypto++