Reputation: 55
I am trying to create a SHA1 hash of a user input and store it in a string value so I can compare it to a text file of known hashes.
To create the hash:
SHA1(password,strlen(password),temp);
print_hex(temp, sizeof(temp));
Convert the hash:
for(i=0;i<sizeof(passHash);i++){
sprintf(&passHash[i], "%02x", temp[i]);
}
printf("%s\n", passHash);
Print_hex:
void print_hex(unsigned char *buf, int len){
int i;
for(i=0;i<len;i++){
printf("%02x",buf[i]);
}
printf("\n");
}
When I run the program with a known hashed password like "password" it shows the right hash with print_hex but not after the sprintf. Therefore, I know I am converting the SHA1 hash incorrectly.
What am I doing wrong?
Upvotes: 0
Views: 1063
Reputation: 9173
You are overwriting in your converted string in consecutive sprintf
calls. Check this:
char passHash[100] = {0,};
for(i=0;i<sizeof(temp);i++){
sprintf(passHash + i * 2, "%02x", temp[i]); // <-- each 2 bytes. e.g: 1 = 01, 255 = FF
}
printf("%s\n", passHash);
Each byte takes 2 character in hex string, so you need to increase sprintf
target buffer by 2. In addition, temp
is the buffer that you are reading from, so your for
loops should loops for sizeof(temp)
, not sizeof(passHash)
.
By the way, this is a sample code that shows your bug and I don't say this is best code.
Upvotes: 4