Hashing
Calculate the SHA-256 digest of a file
Writes some data to a file, then calculates the SHA-256 digest::Digest of
the file’s contents using digest::Context.
use anyhow::Result;
use ring::digest::{Context, Digest, SHA256};
use data_encoding::HEXUPPER;
use std::fs::File;
use std::io::{BufReader, Read, Write};
fn sha256_digest<R: Read>(mut reader: R) -> Result<Digest> {
let mut context = Context::new(&SHA256);
let mut buffer = [0; 1024];
loop {
let count = reader.read(&mut buffer)?;
if count == 0 {
break;
}
context.update(&buffer[..count]);
}
Ok(context.finish())
}
fn main() -> Result<()> {
let path = "file.txt";
let mut output = File::create(path)?;
write!(output, "We will generate a digest of this text")?;
let input = File::open(path)?;
let reader = BufReader::new(input);
let digest = sha256_digest(reader)?;
println!("SHA-256 digest is {}", HEXUPPER.encode(digest.as_ref()));
Ok(())
}
Sign and verify a message with HMAC digest
The hmac::sign method is used to calculate the HMAC digest (also called a tag) of the message using the provided key.
The resulting hmac::Tag structure contains the raw bytes of the HMAC,
which can later be verified withhmac::verify to ensure the message has not been tampered with and comes from a trusted source.
use ring::{hmac, rand};
use ring::rand::SecureRandom;
use ring::error::Unspecified;
fn main() -> Result<(), Unspecified> {
let mut key_value = [0u8; 48];
let rng = rand::SystemRandom::new();
rng.fill(&mut key_value)?;
let key = hmac::Key::new(hmac::HMAC_SHA256, &key_value);
let message = "Legitimate and important message.";
let signature: hmac::Tag = hmac::sign(&key, message.as_bytes());
hmac::verify(&key, message.as_bytes(), signature.as_ref())?;
Ok(())
}