Crypto++ AES加密和解密

kyaa111 5月前 ⋅ 119 阅读

安装

  1. 源码下载 https://cryptopp.com/#download
  2. 用visual studio打开项目
  3. cryptlib项目属性中配置Debug/x64, C/C++ > 代码生成中 配置运行库为MDd, 要保持和引用项目一致
  4. 生成
  5. 目录x64\Output\Debug\cryptlib.lib下就是对应的库了

使用

  1. visual studio创建一个简单项目, 运行库同样MDd
  2. 配置项目属性 C/C++ > 常规 > 附加包含目录 , 填cryptopp的源码路径
  3. 链接器 > 输入 > 附加依赖项 填库文件全路径

示例

#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++