create a sha1 hash from a string in rust

To generate a SHA1 hash in Rust, you can use the sha1 crate which provides a hash function implementation for SHA1.

Here's an example of how to use it:

main.rs
extern crate sha1;

use sha1::{Sha1, Digest};

fn main() {
    let mut hasher = Sha1::new();
    hasher.input(b"hello world");
    let result = hasher.result();

    println!("{:x}", result);
}
194 chars
12 lines

In this example, we first need to import the sha1 crate. We then create a new instance of the Sha1 hasher and input the string we want to hash using the input method.

Finally, we call the result method to get the digest and print it out using the println macro along with the x format specifier to format the digest value as a hexadecimal string.

This will output the following hash:

main.rs
2ef7bde608ce5404e97d5f042f95f89f1c232871
41 chars
2 lines

Note that the input value needs to be a byte array ([u8]), hence the b before the string to convert it to a byte array.

related categories

gistlibby LogSnag