Rust: hash file with sha256

Install the Crate

cargo add sha3 hex

Hash a String

The code is as follows:

use sha3::{Digest, Sha3_256};

let mut hasher = Sha3_256::new();
hasher.update(b"abc");
let hash = hasher.finalize();

println!("{:?}", hash);

At this point, the resulting object is a binary array. To convert it to a hexadecimal string, use hex::encode, as follows:

let hash = hex::encode(&hash);
println!("{:?}", hash);
assert_eq!(hash, "3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532");

Hash a File

use sha3::{Digest, Sha3_256};
use std::fs;

let mut hasher = Sha3_256::new();
// Read the file, please replace with your own file path
let bytes = fs::read("yourfile.path").unwrap();
hasher.update(bytes);
let hash = hasher.finalize();
let hash = hex::encode(&hash);
println!("{:?}", hash);