I am trying to use utility.library's SHA1 hash functions. I thought I had it all correct, but I only get garbage for the final hash.
char SAK_SHA1Hash[20]; struct MessageDigest_SHA *MD_SHA1; if (!(MD_SHA1=(struct MessageDigest_SHA *)AllocVecTags(sizeof(struct MessageDigest_SHA), AVT_Type, MEMF_SHARED, AVT_ClearWithValue, 0, TAG_DONE))) { SAK_EasyRequest(Objects[OID_WINDOW],MainWindow,RequesterTitle,REQIMAGE_ERROR,0,SAK_LocaleString(MSG_COULD_NOT_ALLOCATE_MEMORY),SAK_LocaleString(MSG_TERMINATE)); return(FALSE); } BOOL SAK_GetFileSHA1(STRPTR Path) { unsigned char buf[1024]; int n; FILE *fp; MessageDigest_SHA_Init(MD_SHA1); if (!(fp=fopen(Path,"r"))) return(FALSE); while((n=fread(buf,1,sizeof(buf),fp))>0) MessageDigest_SHA_Update(MD_SHA1,buf,n); fclose(fp); MessageDigest_SHA_Final(MD_SHA1); if (ferror(fp)) return(FALSE); Strlcpy((STRPTR)SAK_SHA1Hash,(STRPTR)MD_SHA1->mdsha_Code,20); return(TRUE); } .............. SAK_GetFileSHA1("C:ftp"); Printf((STRPTR)SAK_SHA1Hash);
The final out is just random garbage characters. What do I have wrong?
First off the returned hash is binary so you can't print it directly like you are doing. Also it is not NUL-terminated so by using Strlcpy() instead of memcpy() or CopyMem() you lose the last byte of the hash.
The following code calculates the hash of a file and prints it out as a hexadecimal string:
I had a hunch about it being in HEX. Didn't know about using memcpy(). I couldn't find any example; maybe you should put your entire reply in the Autodocs for the next person.
Thank you!