create a blake2b hash from a string in rust

To create a Blake2b hash from a string in Rust, you can use the blake2_rfc crate which provides a simple interface to the Blake2 family of hash functions.

First, add blake2_rfc as a dependency in your Cargo.toml file:

[dependencies]
blake2_rfc = "0.2.18"
37 chars
3 lines

Then, in your Rust code, import the crate by adding this to the top of your file:

main.rs
use blake2_rfc::blake2b::Blake2b;
34 chars
2 lines

To hash a string using Blake2b, you can create a new Blake2b object and pass the string to the update method:

main.rs
fn hash_string(input: &str) -> [u8; 64] {
    let mut hasher = Blake2b::new(64);
    hasher.update(input.as_bytes());
    let result = hasher.finalize();
    result.into()
}
174 chars
7 lines

The new method creates a new Blake2b object with a 64-byte output size (i.e. a 512-bit hash). The update method adds the input string to the hash. Finally, the finalize method completes the hash and returns the resulting hash value as a byte array.

You can then call the hash_string function with a string input to get the corresponding Blake2b hash:

main.rs
fn main() {
    let hash = hash_string("hello world");
    println!("{:x}", hash);
}
85 chars
5 lines

This will output the following hash:

main.rs
d1bfd4fb49625bb68401baf19e8dbdd3036497b907c94275738ba244e8b3a3d9a9fce2492b09c7d5eb5b5c73e31e2d6bc7ae6d62f6f9c6c1112701d020bc8c06
129 chars
2 lines

gistlibby LogSnag