Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created March 29, 2026 00:25
Show Gist options
  • Select an option

  • Save rust-play/230519725166a60bf0a3ccf4d52f9c41 to your computer and use it in GitHub Desktop.

Select an option

Save rust-play/230519725166a60bf0a3ccf4d52f9c41 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
use sha2::{Sha256, Digest};
/// A macro that takes a file path string literal, hashes the embedded bytes
/// using SHA-256, and returns a hex-encoded String.
macro_rules! get_file_hash {
($file_path:expr) => {{
let bytes = include_bytes!($file_path);
let mut hasher = Sha256::new();
hasher.update(bytes);
let result = hasher.finalize();
// Convert the GenericArray to a hex string
result.iter()
.map(|b| format!("{:02x}", b))
.collect::<String>()
}};
}
fn main() {
// We can now assign the result of the macro to a variable
let self_hash = get_file_hash!("main.rs");
println!("--- [Self-Audit Report] ---");
println!("Target: main.rs");
println!("SHA-256 Hash: {}", self_hash);
// Example of using the hash in logic
if self_hash.starts_with("e3b0") {
println!("Warning: This hash represents an empty file.");
} else {
println!("Status: Integrity Verified.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment