Getting the SHA256 hash of a file


#1

Is there an easy way in Rust to get a SHA256 hash of a file? I’ve got some fairly large files that I want to get a hash of, but I don’t want to load the whole file in memory.


#2

You can use the sha2 crate - the Sha256 type implements Write, so you can use io::copy to stream the contents of the file through it. Something like this (untested):

let mut file = File::open("my_file.txt")?;
let mut sha256 = Sha256::new();
io::copy(&mut file, &mut sha256)?;
let hash = sha256.result();
println!("hash is: {:x}", hash);