aes 128的加解密算法c++不用openssl库
时间: 2023-07-29 09:10:27 浏览: 53
AES 128是一种对称加密算法,可以使用C++自带的加密库Crypto++进行实现。以下是一个简单的示例代码:
```c++
#include <iostream>
#include <string>
#include <cryptlib.h>
#include <modes.h>
#include <aes.h>
using namespace CryptoPP;
std::string aes_encrypt(const std::string& plaintext, const std::string& key)
{
std::string ciphertext;
try
{
CBC_Mode<AES>::Encryption encryption((byte*)key.c_str(), AES::DEFAULT_KEYLENGTH, (byte*)"0000000000000000");
StringSource(plaintext, true, new StreamTransformationFilter(encryption, new StringSink(ciphertext)));
}
catch (const CryptoPP::Exception& e)
{
std::cerr << e.what() << std::endl;
exit(1);
}
return ciphertext;
}
std::string aes_decrypt(const std::string& ciphertext, const std::string& key)
{
std::string plaintext;
try
{
CBC_Mode<AES>::Decryption decryption((byte*)key.c_str(), AES::DEFAULT_KEYLENGTH, (byte*)"0000000000000000");
StringSource(ciphertext, true, new StreamTransformationFilter(decryption, new StringSink(plaintext)));
}
catch (const CryptoPP::Exception& e)
{
std::cerr << e.what() << std::endl;
exit(1);
}
return plaintext;
}
int main()
{
std::string plaintext = "Hello, world!";
std::string key = "0123456789abcdef";
std::string ciphertext = aes_encrypt(plaintext, key);
std::string decrypted_plaintext = aes_decrypt(ciphertext, key);
std::cout << "Plaintext: " << plaintext << std::endl;
std::cout << "Ciphertext: " << ciphertext << std::endl;
std::cout << "Decrypted plaintext: " << decrypted_plaintext << std::endl;
return 0;
}
```
其中,aes_encrypt和aes_decrypt分别是AES加密和解密函数,传入明文或密文和密钥即可得到对应的结果。需要注意的是,Crypto++中的AES实现默认使用的是128位的密钥长度,因此密钥长度为16字节(128位)。以上代码中使用的是CBC模式,可以根据实际需求选择其他模式。