HMAC (hash-based message authentication code) supports the usage of a key to hash data. This key is kept secret between Bob and Alice, and can be used to authentication both the data and that the sender still knows the secret. Overall HMAC can be used with a range of different hashing methods, such as MD5, SHA-1, SHA-256 (SHA-2) and SHA-3.
HMAC in Rust |
Code
First we create the with:
cargo new hmac
We then go into the blake folder, and add the following to the cargo.toml file:
[package] name = "hmac" version = "1.0.0" authors = ["Bill"] [dependencies] ring="0.16.20" hex = "0.4"
In this case we will use the Ring crate, and which supports a range of cryptographic methods. For this we will use HMAC with SHA-256 hashing:
extern crate ring; extern crate hex; use ring::{hmac}; use std::env; fn main() { let mut message = String::from("Hello world!"); let mut mykey =String::from("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F"); let args: Vec= env::args().collect(); if args.len() >1 { message = args[1].clone(); } if args.len() >2 { mykey = args[2].clone(); } let key_value1 = hex::decode(mykey).expect("Decoding failed"); let key_value =key_value1.as_ref(); let key = hmac::Key::new(hmac::HMAC_SHA256, key_value); let signature = hmac::sign(&key, message.as_bytes()); println!("Message: {}",message); println!("Key (as byte values) {:?}",key_value1); println!("\nSignature: {:?}",signature); let rtn=hmac::verify(&key, message.as_bytes(), signature.as_ref()).is_ok(); if rtn==true { println!("\nSignature checked"); } else { println!("\nHMAC failed") } }
Finally we simply build with:
cargo build
A sample run is:
Message: The quick brown fox jumps over the lazy dog Key (as byte values) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31] Signature: Tag(SHA256:f87ad256151fc7b4c5dffa4adb3ebe911a8eeb8a8ebdee3c2a4a8e5f5ec02c32) Signature checked
To check [here]: