How to hash a string with SHA-256 in Rust

1 Answer

0 votes
use sha2::{Sha256, Digest};

fn sha256(input: &str) -> String {
    // 1. Create a Sha256 hasher
    let mut hasher = Sha256::new();

    // 2. Feed input bytes
    hasher.update(input.as_bytes());

    // 3. Finalize and get the hash bytes (GenericArray<u8, 32>)
    let result = hasher.finalize(); 

    // 4. Convert each byte to two‑digit hex and collect into a String
    result.iter().map(|b| format!("{:02x}", b)).collect::<String>()
}

fn main() {
    let input = "Rust programming language";
    let hash = sha256(input);
    
    println!("Input: {}", input);
    println!("Hash:  {}", hash);
}



/*
run:

Input: Rust programming language
Hash:  df7b36e38addb3eee57d78dde9070c4b9c53ecbe38b546b5937a21e4e58a3a6a

*/

 



answered 4 hours ago by avibootz
...