Romonov
Romonov

Reputation: 8605

mod of an unsigned char from secure hash function

i have an unsigned char test_SHA1[20] of 20 bytes which is a return value from a hash function. With the following code, I get this output

unsigned char test_SHA1[20];
char hex_output[41];
for(int di = 0; di < 20; di++)
{
    sprintf(hex_output + di*2, "%02x", test_SHA1[di]);
}

printf("SHA1 = %s\n", hex_output);

50b9e78177f37e3c747f67abcc8af36a44f218f5

The last 9 bits of this number is 0x0f5 (= 245 in decimal) which I would get by taking a mod 512 of test_SHA1. To take mod 512 of test_SHA1, I do

int x = (unsigned int)test_SHA1 % 512;
printf("x = %d\n", x);

But x turns out to be 158 instead of 245.

Upvotes: 0

Views: 233

Answers (1)

Ted Hopp
Ted Hopp

Reputation: 234857

I suggest doing a bit-wise and with 0x1ff instead of using the % operator.

Upvotes: 1

Related Questions