我正在使用OpenSSL和evp。我的问题是,当我调用EVP_EncryptUpdate
时,输入大小不是16的倍数,该函数正在删除其余字符。
这是我的代码:
string a = "hello";
int ilen;
unsigned char * outbuf = (unsigned char *) malloc(sizeof(unsigned char) * 1024 + EVP_MAX_BLOCK_LENGTH);
unsigned char * inbuff = (unsigned char *) malloc(sizeof(unsigned char) * 1024);
for (int i = 0; i < a.size (); i++)
inbuff[i] = a[i];
EVP_EncryptUpdate(ctx, outbuf, &ilen, inbuff, strlen (inbuff));
在这里,ilen
将为0,但如果我调用它,输入大小为16,它也会返回16。
我可以做些什么来加密一切?
答案 0 :(得分:2)
...with an input size, that is not a multiple of 16, the function is deleting the rest characters... ... ilen will be 0, but if i call it, with an input size of 16, it returns 16...
AES的块大小为16个字节。如果插入1,3,5等字节,则缓冲字节直到16可用。一旦输入16,就可以加密块并将其传递回调用者。
如果插入16个字节,则有足够的字节来加密块并将其传递回调用者。
如果只插入5个左右的字节,然后调用EVP_EncryptFinal
,则密码对象将填充到一个完整的块。填充和加密后,最后一个块(或两个)将传递回调用者。
缓冲的字节保存在上下文对象中。
如果你“丢失”字节,那么你做错了什么。也许你用一个内存错误覆盖了一些东西;或者你没有打电话给EVP_EncryptFinal
。
我可以做些什么来加密一切?
请务必检查返回值,并确保对写入的字节求和:
int written = 0, temp;
rc = EVP_EncryptUpdate(ctx, ..., &temp, ..., ...);
written += temp;
// Repeat calls to EVP_EncryptUpdate
rc = EVP_EncryptFinal(ctx, ..., &temp);
written += temp;
我通常看起来像:
int written = 0, temp;
unsigned char * outbuf = ...;
rc = EVP_EncryptUpdate(ctx, &outbuf[written], &temp, inbuf, insize);
assert(rc == 1);
written += temp;
// Repeat calls to EVP_EncryptUpdate
rc = EVP_EncryptFinal(ctx, &outbuf[written], &temp);
assert(rc == 1);
written += temp;
在EVP_EncryptFinal
之后,written
可以使用outbuf
个字节。
我相信您也可以NULL
传递outbuf
,并在最后的调用中检索所有内容:
int written = 0, temp;
unsigned char * outbuf = ...;
rc = EVP_EncryptUpdate(ctx, NULL, NULL, inbuf, insize);
assert(rc == 1);
// Repeat calls to EVP_EncryptUpdate
rc = EVP_EncryptFinal(ctx, outbuf, &written);
assert(rc == 1);