How to get a hash of a file?

Thanks !
The output matches with sha256sum lorem_ipsum.txt


Edit:

var hashed_writer: std.Io.Writer.Hashing(std.crypto.hash.sha2.Sha256) = .init(&buf); also works.

Whats the use case of .initHasher ?

.init is implemented like this:

pub fn init(buffer: []u8) @This() {
    return .initHasher(.init(.{}), buffer);
}

So it’s initializing the underlying hasher with default options (.{}). Some hashers support extra options to configure the behavior; if you want to use one of those with different options, you would need .initHasher.

2 Likes

Apologies is this is obvious / barking up the wrong tree. Your echo and printf commands are hashing the file name, not the file contents. You probably want something like cat lorem_ipsum.txt | sha256sum.

3 Likes

Just sha256sum lorem_ipsum.txt is enough. That’s how I’m confirming my functions work

Yes, absolutely. I was just pointing out the difference between echoing / printfing a file name, which give you just the name, and cating a file name, which gives you the contents.

3 Likes

:sweat_smile: That was an oversight - I ran the program first, followed by sha256sum on the file, and after seeing that their outputs didn’t match, I ran echo and printf (because bad decision making) to see if their output matches.

(I also ran echo without -n which gave a different hash, but didn’t post the output here).

sha256sum lorem_ipsum.txt and cat lorem_ipsum.txt | sha256sum are right.

3 Likes

Small aside: options to echo are non-portable (see the POSIX specification for the echo utility, which doesn’t mandate any options). Always use printf when you need anything fancier than the base ā€œrepeat the arguments to stdoutā€ functionality.

2 Likes

Adding to this: use printf "%s" "THE THING YOU WANT PRINTED", otherwise you risk the thing you’re trying to print having % formatting escape sequences.

3 Likes