Reputation: 367
I've been trying to compute md5 hash using crypto API but have faced a lot of issues.
char * getHashedKey(char *keybuf) {
char * output;
struct scatterlist sg;
struct crypto_hash *tfm;
struct hash_desc desc;
int i;
printk("%s received keybuf %s %d\n", __func__, keybuf, strlen(keybuf));
output = kmalloc(sizeof(*output) * 16, GFP_KERNEL);
memset(output, 0x00, 16);
// works if I overwrite value like this
//keybuf = "abcdef012345";
tfm = crypto_alloc_hash("md5", 0, CRYPTO_ALG_ASYNC);
desc.tfm = tfm;
desc.flags = 0;
sg_init_one(&sg, keybuf, strlen(keybuf));
// tried type casting too
//sg_init_one(&sg, (u8 *) keybuf, strlen(keybuf));
crypto_hash_init(&desc);
crypto_hash_update(&desc, &sg, strlen(keybuf));
crypto_hash_final(&desc, output);
for(i = 0; i < 16; i++)
{
printk("%x", output[i]);
}
printk("\n");
return output;
}
Here's what I tried: 1. If "output" is unsigned char, I get correct output but not when I'm using char.
If I over write the value of keybuf, only then it works.
I tried type casting keybuf as (u8*) as mentioned in some forums but that doesn't work too
The distorted output by using char is:
3ffffffe9ffffffb7ffffffb472ffffffe0ffffffed41225affffffebffffffdaffffffd3ffffffbaffffffabffffffde
Can someone help me with this?
Upvotes: 0
Views: 178
Reputation:
You have two display issues.
First: Passing a char
value -- implicitly a signed char
-- as an argument to printf()
causes it to be extended to a signed int
. As a result, passing a value with the high bit set (e.g, 0xe9
, the second byte in your sample output) will cause it to be sign-extended to 0xffffffe9
and printed as such.
To fix this, declare output
as an array of unsigned char
, or the equivalent type u8
.
Second: You are printing each byte using the %x
format string, with no padding specified. This will cause values between 0x0
and 0xf
to be printed as a single character instead of two, resulting in ambiguous output.
To fix this, use the %02x
format string.
Upvotes: 1