create a sha256 hash from a string in rust

To create a SHA256 hash in Rust, you can use the sha2 crate. Here's an example:

main.rs
use sha2::{Sha256, Digest};

fn main() {
    let input_string = "This is some string to hash";
    let mut hasher = Sha256::new();
    hasher.update(input_string.as_bytes());
    let result = hasher.finalize();
    println!("SHA256 hash: {:x}", result);
}
256 chars
10 lines

In this example, we first import the necessary types from the sha2 crate. Then, we define an example string to hash. We create a new Sha256 hasher using the new() method, update it with the bytes from our input string using the update() method, and finalize it to get the resulting hash using the finalize() method. Finally, we print the resulting hash in hexadecimal format using the :x format specifier.

Note that this example uses the std::hash::Hash trait. If you want to use a different hashing algorithm or more advanced cryptographic constructs, you may need to use a different crate or implement your own hash function.

gistlibby LogSnag