Determine size of decrypted data from gcry_cipher_decrypt?

给你一囗甜甜゛ 提交于 2019-12-02 19:17:28

问题


I am using AES/GCM, but the following is a general question for other modes, like AES/CBC. I have the following call into libgcrypt:

#define COUNTOF(x) ( sizeof(x) / sizeof(x[0]) )
#define ROUNDUP(x, b) ( (x) ? (((x) + (b - 1)) / b) * b : b)

const byte cipher[] =  { 0xD0,0x6D,0x69,0x0F ... };
byte recovered[ ROUNDUP(COUNTOF(cipher), 16) ];
...

err = gcry_cipher_decrypt(
    handle,             // gcry_cipher_hd_t
    recovered,          // void *
    COUNTOF(recovered), // size_t
    cipher,             // const void *
    COUNTOF(cipher));   // size_t

I cannot figure out how to determine what the size of the resulting recovered text is. I've checked the Working with cipher handles reference, and its not discussed (and there are 0 hits for 'pad). I also checked the libgrcrypt self tests in tests/basic.c and tests/fipsdrv.c, but they use the same oversized buffer and never prune the buffer to the actual size.

How do I determine the size of the data returned to me in the recovered buffer?


回答1:


You need to apply a padding scheme to your input, and remove the padding after the decrypt. gcrypt doesn't handle it for you.

The most common choice is PKCS#7. A high level overview is that you fill the unused bytes in your final block with the number of padded bytes (block_size - used_bytes). If your input length is a multiple of the block size, you follow it with a block filled with block_size bytes.

For example, with 8-byte blocks and 4 bytes of input, your raw input would look like:

AB CD EF FF 04 04 04 04

When you do the decrypt, you take the value of the last byte of the last block, and remove that many bytes from the end.



来源:https://stackoverflow.com/questions/28845263/determine-size-of-decrypted-data-from-gcry-cipher-decrypt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!