Bakus123
Bakus123

Reputation: 1399

MD5 - add message length

I would like to create block for MD5 algorithm. This is my code:

uint8_t buffer[64];
for (int i = size + 1; i < 56; i++)
    buffer[i] = 0;

But I don't know how can I add message length on the last 64bits. Any idea?

Upvotes: 0

Views: 105

Answers (1)

Giorgi Moniava
Giorgi Moniava

Reputation: 28685

You declared buffer of length 8, how come you expect this to work:

for (int i = size + 1; i < 56; i++)
    buffer[i] = 0;

Out of bounds access?

Ok you said from 56th element you want to store length. Why not do something like this:

memcpy(&buffer[56], &length, sizeof(int)); // you may want to check sizeof(int) on your machine to know how many bytes were written

but you should be careful about endianness. This will write the length according to the endianness your machine has. If you want to store it in some particular endianness maybe you can do it manually using bit wise operators. Check some more info here, and here

If you want length to have fixed size, you can declare it as uint32_t and use 4 as last parameter in memcpy directly.

Upvotes: 1

Related Questions