Reputation: 175
I'm trying to hash a file on my system and the hash in my C++ code is the correct length but it's a different hash that what I get when I $ echo -n file.txt | sha256sum
I've tried to implement a mixture of what I've seen so far on stackoverflow and finally got something to almost work.
void sha256_file(const std::string &fn)
{
FILE *file;
unsigned char buf[8192];
unsigned char output[SHA256_DIGEST_LENGTH];
size_t len;
SHA256_CTX sha256;
file = fopen(fn.c_str(), "rb");
if(file == NULL)
// do whatever
else
{
SHA256_Init(&sha256);
while((len = fread(buf, 1, sizeof buf, file)) != 0)
SHA256_Update(&sha256, buf, len);
fclose(file);
SHA256_Final(output, &sha256);
for(int i = 0; i < SHA256_DIGEST_LENGTH; i++)
printf("%02x", output[1]);
printf("\n");
}
Please excuse me I'm trying to learn how to use this with the little documentation and most people are just trying to hash short strings.
$ echo -n file.txt | sha256sum
is what I'm using to check the hash but the outputs are different. I'd copy paste but it's on another system.
Upvotes: 0
Views: 1410
Reputation: 5478
Easy, you did [1]
instead of [i]
in your print loop.
for(int i = 0; i < SHA256_DIGEST_LENGTH; i++)
printf("%02x", output[1]);
should be
for(int i = 0; i < SHA256_DIGEST_LENGTH; i++)
printf("%02x", output[i]);
Silly Latin alphabet!
Upvotes: 1