I want to generate an authentication token in Rust. I tried to generate a random key with ring::hmac
, like so:
use ring::{hmac, rand};
let rng = rand::SystemRandom::new();
let key = hmac::Key::generate(hmac::HMAC_SHA256, &rng)?;
How can I then make an hexadecimal string out of key
? Or is there a better way to generate an hexadecimal, secure token in Rust?
If you are creating the Key
yourself you can use Key::new()
instead of Key::generate
, which allows for specifying the key_value
explicitily:
use ring::{digest, hmac, rand};
fn main() {
let msg = "hello, world";
let rng = rand::SystemRandom::new();
let key_value: [u8; digest::SHA256_OUTPUT_LEN] = rand::generate(&rng).unwrap().expose();
let hex = key_value.iter().map(|b| format!("{:02X}", b)).collect::<String>();
println!("{}", hex);
let s_key = hmac::Key::new(hmac::HMAC_SHA256, key_value.as_ref());
let _tag = hmac::sign(&s_key, msg.as_bytes());
}
Here is the link to the Playground.