开发者

Number of bytes in a binary character pointer

开发者 https://www.devze.com 2023-02-13 15:27 出处:网络
I have a char * that contains a binary encrypted string (using AES-128 this is the encrypted output).

I have a char * that contains a binary encrypted string (using AES-128 this is the encrypted output).

I need to figure out how many bytes are in the char * (since AES 128 uses a 16 byte block size it should b开发者_如何学运维e a multiple of 16). What is the best way to determine the size of a char * that contains binary data? Strlen and sizeof do not seem to be producing the right results here (results are not increments of 16). I can loop through the ascii values of the string by simply doing printf("%d",ptr[i]) when I loop through using i between 0 and some arbitrarily large number.

Any ideas here ?


A char* does not have an explicit size defined for the buffer it points to in C. It is only the address of the first char in the buffer and nothing more. If you need the size of the buffer, pass it in a separate variable, like so:

void decryptBuffer(char* buffer, size_t n)

Note: sizeof(buffer) will only give you the size of the pointer, not the number of bytes it points to!


There is no way to know how long the encrypted string is. You know that it's more than 16bytes and less than the buffer size. You must know the number of blocks.

With that said, if you really can't get the number of blocks, try to decrypt 16bytes, and check if it's what you need. If not, decrypt 32bytes and perform the check until the end of the buffer or until you have what you need.


The size of the char* depends on your computer's address bus length and is being stored in the stack of your program. For instance a 32 bit pointer should have a size of 4 bytes. Indeed you can find that out using sizeof(char*).

The char* points to a memory address and you can't just know what is the allocated block. If at that address you actually have a string you could just read until you reach the string terminator '\0'. However if it just points to binary data, my solution would be to encode the length of the data at the beginning of your encoded string and use it as a header so you'll know when to stop.

But how did you get an encrypted object in the memory anyway? didn't you use a structure of some sort? I'm guessing you stored the encrypted string as a string.

Please provide more details..


As other people have pointed out, there's no way to figure out how many bytes a char * points to.

AES-128 algorithms encrypt data in blocks of 16 bytes, and if the input string is not a multiple of 16 bytes the algorithm will use a padding scheme.

So the number of bits in the encrypted output will be equal to the number of bits in your input string, provided your input is a multiple of 16 bytes. If not then it will have padded to the nearest 16 byte block. You really need the size of the input string to work this out though.

0

精彩评论

暂无评论...
验证码 换一张
取 消