DEV Community

BC
BC

Posted on

Day21:Compute md5, sha256 and hmac - 100DayOfRust

Cargo.toml

[dependencies]
rust-crypto = "^0.2"
hex = "^0.4"
Enter fullscreen mode Exit fullscreen mode

main.rs

use crypto::mac::Mac;
use crypto::digest::Digest;
use crypto::md5::Md5;
use crypto::sha2::Sha256;
use crypto::hmac::Hmac;
use std::fs;

fn main() {
    let content = fs::read_to_string("main.rs").unwrap();
    let mut md5hasher = Md5::new();
    md5hasher.input_str(&content);
    let hash = md5hasher.result_str();
    println!("md5 is {}", hash);

    let mut sha2hasher = Sha256::new();
    sha2hasher.input_str(&content);
    let hash = sha2hasher.result_str();
    println!("sha256 is {}", hash);

    let mut hmacor = Hmac::new(Sha256::new(), "key".as_bytes());
    hmacor.input("this is a string".as_bytes());
    let hash = hmacor.result();
    println!("hmac is {}", hex::encode(hash.code()));
}
Enter fullscreen mode Exit fullscreen mode

Result

md5 is 86f3786c855da3d6a5aa226a86a95f15
sha256 is e05e040cae828af17ab37b351e322dd31faaf7aee9eb8829e7a025fb0b5e3871
hmac is 64bf374b05b1611beecbd917c75954975384c022964e7b30d5501e6c4846a6ff
Enter fullscreen mode Exit fullscreen mode

Top comments (0)