C++ 使用 Crypto++ 库实现 AES 加密
Crypto++ 是一个开源的密码学库,可以用于实现各种加密算法。下面是使用 Crypto++ 库加密 AES 的示例代码:
#include <iostream>
#include <string>
#include <cryptopp/aes.h>
#include <cryptopp/modes.h>
#include <cryptopp/filters.h>
#include <cryptopp/hex.h>
int main() {
// 密钥和明文
std::string key = '0123456789abcdef';
std::string plaintext = 'Hello, Crypto++!';
// 设置加密模式和填充方式
CryptoPP::AES::Encryption aesEncryption((byte*)key.c_str(), CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption(aesEncryption, (byte*)key.c_str());
// 加密
std::string ciphertext;
CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink(ciphertext));
stfEncryptor.Put(reinterpret_cast<const unsigned char*>(plaintext.c_str()), plaintext.length());
stfEncryptor.MessageEnd();
// 将加密结果转换为十六进制字符串
std::string encoded;
CryptoPP::HexEncoder encoder(new CryptoPP::StringSink(encoded));
encoder.Put(reinterpret_cast<const unsigned char*>(ciphertext.c_str()), ciphertext.length());
encoder.MessageEnd();
std::cout << "Ciphertext: " << encoded << std::endl;
return 0;
}
注意,这只是一个简单的示例,实际中还需要考虑密钥的生成和管理、数据的完整性验证等其他安全问题。
原文地址: https://www.cveoy.top/t/topic/bNQR 著作权归作者所有。请勿转载和采集!