rust 22 lines · 5 steps

Streaming a SHA-256 hash of a file in Rust

Compute a file's SHA-256 digest by reading it in fixed-size chunks so memory stays constant regardless of file size.

Explained by highlit
1use std::fs::File;
2use std::io::{self, Read};
3use std::path::Path;
4 
5use sha2::{Digest, Sha256};
6 
7pub fn sha256_file(path: impl AsRef<Path>) -> io::Result<String> {
8 let mut file = File::open(path)?;
9 let mut hasher = Sha256::new();
10 let mut buffer = [0u8; 64 * 1024];
11 
12 loop {
13 let read = file.read(&mut buffer)?;
14 if read == 0 {
15 break;
16 }
17 hasher.update(&buffer[..read]);
18 }
19 
20 let digest = hasher.finalize();
21 Ok(hex::encode(digest))
22}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Reading a file in a fixed buffer keeps memory flat no matter how large the file grows.
  2. 2Hashers accept data incrementally, so you never need the whole input in memory at once.
  3. 3Using `impl AsRef<Path>` lets callers pass strings, `PathBuf`, or `Path` interchangeably.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Streaming a SHA-256 hash of a file in Rust — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code