create a blake2s hash from a string in rust

To create a Blake2s hash from a string in Rust, you can use the blake2::Blake2s struct from the blake2 crate. First, add the blake2 dependency to your Cargo.toml file:

[dependencies]
blake2 = "0.9.0"
32 chars
3 lines

Then, use the blake2::digest::Digest trait to create a hash from your string:

main.rs
use blake2::{Blake2s, Digest};

fn main() {
    let input_str = "hello world";
    let mut hasher = Blake2s::new();
    hasher.update(input_str.as_bytes());
    let result = hasher.finalize();
    let hash_hex = format!("{:x}", result);
    println!("Blake2s hash of \"{}\": {}", input_str, hash_hex);
}
304 chars
11 lines

In this example, we create a new Blake2s instance and call update on it with the bytes of our input string. Then, we call finalize to compute the hash value. Finally, we format the result as a hexadecimal string and print it. The output should be:

main.rs
Blake2s hash of "hello world": 34f9d62c15c3cf4c4dda8d476b4c02faf1a4e5f47b721d20c4ac8a9254945d0b
96 chars
2 lines

gistlibby LogSnag