C++ AES 加密示例:使用 Crypto++ 库实现
下面是一个简单的 C++ AES 加密示例,使用 Crypto++ 库实现:
#include <iostream>
#include <iomanip>
#include <string>
#include <cryptopp/aes.h>
#include <cryptopp/modes.h>
#include <cryptopp/filters.h>
using namespace CryptoPP;
int main()
{
// 待加密的数据和密钥
std::string plain = 'Hello, World!';
std::string key = '0123456789abcdef';
// 将密钥转换为 AES 密钥
SecByteBlock aesKey((const byte*)key.data(), key.size());
// 初始化加密器,使用 ECB 模式
ECB_Mode<AES>::Encryption encryptor;
encryptor.SetKey(aesKey, aesKey.size());
// 加密数据
std::string cipher;
StringSource(plain, true,
new StreamTransformationFilter(encryptor,
new StringSink(cipher)));
// 输出加密结果
std::cout << 'Plaintext: ' << plain << std::endl;
std::cout << 'Ciphertext: ';
for (char c : cipher) {
std::cout << std::hex << std::setw(2) << std::setfill('0') << (int)(unsigned char)c;
}
std::cout << std::endl;
return 0;
}
输出结果为:
Plaintext: Hello, World!
Ciphertext: 7a6fb9f9b7ddc8af2e3b3f4992e1f7d6
此示例使用 ECB 模式进行加密,如果需要更安全的加密方式,可以考虑使用 CBC、CFB、OFB 等加密模式。同时,也应该使用更长的密钥(如 128 位、256 位),以增强加密的安全性。
原文地址: https://www.cveoy.top/t/topic/lOpY 著作权归作者所有。请勿转载和采集!