c++ - 在 Crypto++ 中将密钥传递给 AES 解密
问题描述
我已经为此问题进行了很多搜索,但没有找到任何解决方案。在我目前的项目中,我必须使用发送者接收者表单来加密图像。所以我必须在发送方部分生成一个密钥来加密文件,并且我必须使用相同的密钥(作为参数传递给 main)来获取原始数据,以继续执行程序。
我将密钥保存在文本文件中:
void GetKeyAndIv() {
// Initialize the key and IV
prng.GenerateBlock( key, key.size() );
prng.GenerateBlock(iv, iv.size());
};
/*********************Begin of the Function***********************/
//Function encrypt a file (original file) and store the result in another file (encrypted_file)
void Encrypt(std::string original_file, std::string encrypted_file_hex,string encrypted_file,string binary) {
ofstream out;
out.open("Key.txt");
out.clear();
out<<"key = "<< key<<endl;
out<<"iv = "<< iv<<endl;
string cipher, encoded;
//Getting the encryptor ready
CBC_Mode< CryptoPP::AES >::Encryption e;
e.SetKeyWithIV( key, key.size(), iv );
try
{
ifstream infile(original_file.c_str(), ios::binary);
ifstream::pos_type size = infile.seekg(0, std::ios_base::end).tellg();
infile.seekg(0, std::ios_base::beg);
//read the original file and print it
string temp;
temp.resize(size);
infile.read((char*)temp.data(), temp.size());
infile.close();
// Encryption
CryptoPP::StringSource ss( temp, true,
new CryptoPP::StreamTransformationFilter( e,
new CryptoPP::StringSink( cipher )//,
//CryptoPP::BlockPaddingSchemeDef::NO_PADDING
) // StreamTransformationFilter
); // StringSource
std::ofstream outfile1(encrypted_file.c_str(),ios::out | ios::binary);
outfile1.write(cipher.c_str() , cipher.size());
}
catch( const CryptoPP::Exception& e )
{
cout <<"Encryption Error:\n" <<e.what() << endl;
system("pause");
exit(1);
}
然后我使用以下代码将其传递给客户端:
int main(int argc, char* argv[])
{
.....
string s1=argv[7];
SecByteBlock b1(reinterpret_cast<const byte*>(&s1[0]), s1.size());
string s2=argv[8];
SecByteBlock iv1(reinterpret_cast<const byte*>(&s2[0]), s2.size());
.....
}
尝试使用以下代码解密文件时出现错误
void Decrypt(std::string encrypted_file,SecByteBlock key,SecByteBlock iv,string decrypted_file) {
string recovered;
try
{
// Read the encrypted file contents to a string as binary data.
std::ifstream infile(encrypted_file.c_str(), std::ios::binary);
const std::string cipher_text((std::istreambuf_iterator<char>(infile)),
std::istreambuf_iterator<char>());
infile.close();
CBC_Mode< CryptoPP::AES >::Decryption d;
d.SetKeyWithIV( key, key.size(), iv );
解密错误: StreamTransformationFilter:发现无效的 PKCS #7 块填充
这意味着我在解密过程中有不同的密钥。为什么会发生这种情况,以及是否有人可以帮助解决此问题。
解决方案
我将 CBC_Mode 更改为另一种模式,ODB_Mode 为我工作
推荐阅读
- .net - 无法使用 JsonProvider 加载类型
- angular - 我应该访问商店以使用状态值作为 NGRX 效果的有效负载吗?
- python - 错误转换为其他人似乎没有得到的python中的浮点数
- matplotlib - 提取matplotlib在构建拟合曲线时使用的点
- c# - 重新启动浏览器时保持用户登录
- javascript - 如何有条件地触发 Angular 中的点击事件?
- python - 减去在多个列值上连接的两个 Pandas DataFrame
- python - 在列表中附加值的逻辑顺序(python)
- django - 在 Django 中,你如何引用你的项目 urls.py 的 URL?
- python - PyParsing - 匹配字符串后跟子字符串