create a sha3_256 hash from a string in rust

To create a Sha3_256 hash from a string in Rust, you can use the digest crate, which provides a simple and efficient interface for hashing data.

First, add the following dependency to your Cargo.toml file:

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

Then, you can use the following code snippet to create a Sha3_256 hash from a string:

main.rs
use digest::Digest;
use sha3::Sha3_256;

fn main() {
    let input = "example string";
    let mut hasher = Sha3_256::new();
    hasher.update(input.as_bytes());
    let result = hasher.finalize();
    println!("{:x}", result);
}
230 chars
11 lines

In this code, we first create a new instance of the Sha3_256 hasher with Sha3_256::new(). We then update the hasher with the input string by calling hasher.update(input.as_bytes()). Finally, we obtain the hash value by calling hasher.finalize() and print it in hex format by passing it to println!("{:x}", result).

Note that the finalize() method consumes the hasher and returns the hash value, so you should only call it once. If you need to hash multiple inputs, create a new hasher for each input instead.

gistlibby LogSnag