OpenSSL AES_cfb128_encrypt C++(OpenSSL AES_cfb128_encrypt C++)
问题描述
我试图实现一个非常"简单的加密/解密示例.我需要它用于我想加密一些用户信息的项目.我无法加密整个数据库,只能加密表中的某些字段.
I tried to implement a "very" simple encryption/decryption example. I need it for a project where I would like to encrypt some user information. I can't encrypt the whole database but only some fields in a table.
数据库和项目的其余大部分工作,除了加密:这是它的简化版本:
The database and most of the rest of the project works, except the encryption: Here is a simplified version of it:
#include <openssl/aes.h>
#include <openssl/evp.h>
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
/* ckey and ivec are the two 128-bits keys necessary to
en- and recrypt your data. Note that ckey can be
192 or 256 bits as well
*/
unsigned char ckey[] = "helloworldkey";
unsigned char ivec[] = "goodbyworldkey";
int bytes_read;
unsigned char indata[AES_BLOCK_SIZE];
unsigned char outdata[AES_BLOCK_SIZE];
unsigned char decryptdata[AES_BLOCK_SIZE];
/* data structure that contains the key itself */
AES_KEY keyEn;
/* set the encryption key */
AES_set_encrypt_key(ckey, 128, &keyEn);
/* set where on the 128 bit encrypted block to begin encryption*/
int num = 0;
strcpy( (char*)indata , "Hello World" );
bytes_read = sizeof(indata);
AES_cfb128_encrypt(indata, outdata, bytes_read, &keyEn, ivec, &num, AES_ENCRYPT);
cout << "original data: " << indata << endl;
cout << "encrypted data: " << outdata << endl;
AES_cfb128_encrypt(outdata, decryptdata, bytes_read, &keyEn, ivec, &num, AES_DECRYPT);
cout << "input data was: " << decryptdata << endl;
return 0;
}
但是解密"数据的输出是一些随机字符,但是每次执行代码后都是一样的.outdata
每次执行都会改变...
But the output of "decrypted" data are some random characters, but they are the same after every execution of the code. outdata
changes with every execution...
我尝试调试并寻找解决方案,但找不到任何解决方案.
现在我的问题是,这里出了什么问题?还是我完全误解了提供的功能?
I tried to debug and search for a solution, but I couldn't find any solution for my problem.
Now my question, what is going wrong here? Or do I completely misunderstand the provided functions?
推荐答案
问题在于 AES_cfb128_encrypt
修改了 ivec
(为了允许链接,必须这样做).您的解决方案是创建 ivec
的副本并在每次调用 AES_cfb128_encrypt
之前对其进行初始化,如下所示:
The problem is that AES_cfb128_encrypt
modifies the ivec
(it has to in order to allow for chaining). Your solution is to create a copy of the ivec
and initialize it before each call to AES_cfb128_encrypt
as follows:
const char ivecstr[AES_BLOCK_SIZE] = "goodbyworldkey ";
unsigned char ivec[AES_BLOCK_SIZE];
memcpy( ivec , ivecstr, AES_BLOCK_SIZE);
然后在第二次调用 AES_cfb128_encrypt
之前重复 memcpy
.
Then repeat the memcpy
before your second call to AES_cfb128_encrypt
.
注意 1:您的初始向量太短了一个字节,所以我在它的末尾添加了一个明确的附加