EVP_EncryptUpdate,输入大小必须是16的倍数

时间:2014-07-19 19:06:31

标签: openssl size buffer

我正在使用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。

我可以做些什么来加密一切?

1 个答案:

答案 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);
相关问题