I have computed the SHA1
for a piece of data and I need to store it into a file to be read by another person later. The SHA1
gives the output as 190 bit's
, but I can't store as bits into a file, fputc()
function does it characters which means bytes.
So I want to either store it as bytes into the file or as its hexadecimal
representation (preferably). In C
, so far I can only get it to print the hash to the terminal as the hexadecimal representation (using a way I found in another question posted in this site), but I can't figure out how to store it to a file properly.
Please help!
If you want to write the SHA1 digest as binary digest in the file, you can use:
fwrite ( &sha1_digest, sizeof(sha1_digest), 1, stream );
Where stream
is a FILE* opened in binary mode.
If you want to save it as hexadecimal string, you can do a loop :
char *p=(void*)&sha1_digest;
int i=sizeof(sha1_digest);
while (i--)
fprintf (stream, "%02x",*p++);
where tream is a FILE* opened in text or binary mode
I assumed that sha1_digest
was a structure. If it's an array, you don't need the &
and if the array is not fixed size, then you must provide the size of the digest (because in this case, sizeof()
would return the sizeof a pointer isntead of the array.)
You are certainly aware, but SHA1 is no longer considered as a safe hash, if your use is somewhat related to security.