DEV Community

BC
BC

Posted on

Day36:Calculate sha1 with crypto and sha1 crate - 100DayOfRust

There are 2 crates you can use to calculate the sha1 value: crypto and sha1:

Cargo.toml:

[dependencies]
rust-crypto = "0.2.36"
sha1 = "0.6.0"
Enter fullscreen mode Exit fullscreen mode

Example code:

use crypto;
use crypto::digest::Digest;
use sha1; 


fn main() {
    // use crypto crate to get sha1 hexdigest
    let s = "hello world";
    let mut hasher1 = crypto::sha1::Sha1::new();
    hasher1.input_str(s);
    let hex1 = hasher1.result_str();
    println!("digest: {}", hex1);

    // use sha1 crate to get sha1 hexdigest, simpler
    let hex2 = sha1::Sha1::from(s).digest();
    println!("digest: {}", hex2);
}
Enter fullscreen mode Exit fullscreen mode

Cargo run:

digest: 2aae6c35c94fcfb415dbe95f408b9ce91ee846ed
digest: 2aae6c35c94fcfb415dbe95f408b9ce91ee846ed
Enter fullscreen mode Exit fullscreen mode

To calculate other digest like md5, sha256 or hmac, you can check my previous post here.

Reference:

Top comments (0)