Hashing
Choosing between ring and RustCrypto
ringis a single crate with a fixed set of algorithms, built on C and assembly code from BoringSSL. Choose it when SHA-2, HMAC and PBKDF2 are all you need and you want one dependency with one API.- RustCrypto is a family of separate crates (
sha2,hmac,pbkdf2,argon2) written in Rust that share the traits of thedigestcrate, so the hash function is a type parameter. Choose it when you want generic code, algorithmsringlacks such as Argon2, or a build without C. - Both are pre-1.0, so their APIs may still change.
The RustCrypto versions of the recipes follow the ring ones. For patterns that
use the shared traits, see Extensible RustCrypto.
Calculate the SHA-256 digest of a file
ring data-encoding Cryptography
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 data_encoding::HEXUPPER;
use ring::digest::{Context, Digest, SHA256};
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::error::Unspecified;
use ring::rand::SecureRandom;
use ring::{hmac, rand};
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(())
}
Salt and hash a password with PBKDF2
ring data-encoding Cryptography
Uses ring::pbkdf2 to hash a salted password using the PBKDF2 key derivation
function pbkdf2::derive. Verifies the hash is correct with
pbkdf2::verify. The salt is generated using
SecureRandom::fill, which fills the salt byte array with
securely generated random numbers.
use data_encoding::HEXUPPER;
use ring::error::Unspecified;
use ring::rand::SecureRandom;
use ring::{digest, pbkdf2, rand};
use std::num::NonZeroU32;
fn main() -> Result<(), Unspecified> {
const CREDENTIAL_LEN: usize = digest::SHA512_OUTPUT_LEN;
let n_iter = NonZeroU32::new(100_000).unwrap();
let rng = rand::SystemRandom::new();
let mut salt = [0u8; CREDENTIAL_LEN];
rng.fill(&mut salt)?;
let password = "Guess Me If You Can!";
let mut pbkdf2_hash = [0u8; CREDENTIAL_LEN];
pbkdf2::derive(
pbkdf2::PBKDF2_HMAC_SHA512,
n_iter,
&salt,
password.as_bytes(),
&mut pbkdf2_hash,
);
println!("Salt: {}", HEXUPPER.encode(&salt));
println!("PBKDF2 hash: {}", HEXUPPER.encode(&pbkdf2_hash));
let should_succeed = pbkdf2::verify(
pbkdf2::PBKDF2_HMAC_SHA512,
n_iter,
&salt,
password.as_bytes(),
&pbkdf2_hash,
);
let wrong_password = "Definitely not the correct password";
let should_fail = pbkdf2::verify(
pbkdf2::PBKDF2_HMAC_SHA512,
n_iter,
&salt,
wrong_password.as_bytes(),
&pbkdf2_hash,
);
assert!(should_succeed.is_ok());
assert!(!should_fail.is_ok());
Ok(())
}
Calculate the SHA-256 digest of a file with sha2
sha2 data-encoding Cryptography
Use sha2 when you want the hash function to be a type parameter; see
Choosing between ring and RustCrypto. digest_reader works with any hash that
implements Digest, so moving from Sha256 to Sha512 only changes
the type argument. Data is fed to the hasher with Digest::update and the
result is returned by Digest::finalize.
use anyhow::Result;
use data_encoding::HEXLOWER;
use sha2::{Digest, Sha256, Sha512};
use std::fs::File;
use std::io::{BufReader, Read, Write};
/// Hashes everything `reader` yields with any hash that implements [`Digest`].
fn digest_reader<D: Digest, R: Read>(mut reader: R) -> Result<Vec<u8>> {
let mut hasher = D::new();
let mut buffer = [0; 1024];
loop {
let count = reader.read(&mut buffer)?;
if count == 0 {
break;
}
hasher.update(&buffer[..count]);
}
Ok(hasher.finalize().to_vec())
}
fn main() -> Result<()> {
let dir = tempfile::tempdir()?;
let path = dir.path().join("file.txt");
let mut output = File::create(&path)?;
write!(output, "We will generate a digest of this text")?;
let sha256 = digest_reader::<Sha256, _>(BufReader::new(File::open(&path)?))?;
println!("SHA-256 digest is {}", HEXLOWER.encode(&sha256));
// Switching algorithms only changes the type parameter.
let sha512 = digest_reader::<Sha512, _>(BufReader::new(File::open(&path)?))?;
println!("SHA-512 digest is {}", HEXLOWER.encode(&sha512));
Ok(())
}
Sign and verify a message with HMAC using hmac and sha2
Use hmac when the hash function should be chosen with a type alias; see
Choosing between ring and RustCrypto. Hmac wraps any hash from the
RustCrypto family, so type HmacSha256 = Hmac<Sha256> becomes SHA-512 by
changing one word. Mac::finalize computes the tag and
Mac::verify_slice compares a tag in constant time.
use anyhow::Result;
use hmac::{Hmac, KeyInit, Mac};
use sha2::Sha256;
// Changing the hash function is a one-line change, for example to `Sha512`.
type HmacSha256 = Hmac<Sha256>;
fn main() -> Result<()> {
let mut key_value = [0u8; 48];
getrandom::fill(&mut key_value)?;
let message = "Legitimate and important message.";
let mut signer = HmacSha256::new_from_slice(&key_value)?;
signer.update(message.as_bytes());
let tag = signer.finalize().into_bytes();
// `verify_slice` compares the tags in constant time.
let mut verifier = HmacSha256::new_from_slice(&key_value)?;
verifier.update(message.as_bytes());
verifier.verify_slice(&tag)?;
let mut tampered = HmacSha256::new_from_slice(&key_value)?;
tampered.update(b"Tampered message.");
assert!(tampered.verify_slice(&tag).is_err());
Ok(())
}
Salt and hash a password with PBKDF2 using pbkdf2
Use this form when you want to store a single string per user; see
Choosing between ring and RustCrypto. Pbkdf2::hash_password generates a
random salt and returns a PHC string such as
$pbkdf2-sha256$i=600000,l=32$salt$hash, which holds the algorithm, iteration
count, salt and hash together. Pbkdf2::verify_password reads those
parameters back out of the string, so the iteration count can be raised later
without breaking old hashes.
This recipe requires the
phcfeature flag ofpbkdf2to be enabled inCargo.toml.
use pbkdf2::Pbkdf2;
use pbkdf2::password_hash::{PasswordHasher, PasswordVerifier};
use pbkdf2::phc::PasswordHash;
fn main() -> Result<(), pbkdf2::password_hash::Error> {
let password = "Guess Me If You Can!";
// A random salt is generated and stored in the PHC string along with the
// algorithm and its parameters.
let hash = Pbkdf2::default()
.hash_password(password.as_bytes())?
.to_string();
println!("PBKDF2 hash: {hash}");
let parsed = PasswordHash::new(&hash)?;
assert!(
Pbkdf2::default()
.verify_password(password.as_bytes(), &parsed)
.is_ok()
);
assert!(
Pbkdf2::default()
.verify_password(b"Definitely not the correct password", &parsed)
.is_err()
);
Ok(())
}
Salt and hash a password with Argon2
Use Argon2 for new password storage unless you need a FIPS-approved algorithm;
see Choosing between ring and RustCrypto. ring has no Argon2.
Argon2::default selects Argon2id with the crate’s default memory and time
cost. Argon2::hash_password generates a random salt and returns a PHC string
that includes those parameters, and Argon2::verify_password checks a
password against it.
use argon2::Argon2;
use argon2::password_hash::phc::PasswordHash;
use argon2::password_hash::{PasswordHasher, PasswordVerifier};
fn main() -> Result<(), argon2::password_hash::Error> {
let password = "Guess Me If You Can!";
// Argon2id with the default parameters and a random salt. The result is a
// PHC string such as `$argon2id$v=19$m=...,t=...,p=...$salt$hash`.
let hash = Argon2::default()
.hash_password(password.as_bytes())?
.to_string();
println!("Argon2 hash: {hash}");
let parsed = PasswordHash::new(&hash)?;
assert!(
Argon2::default()
.verify_password(password.as_bytes(), &parsed)
.is_ok()
);
assert!(
Argon2::default()
.verify_password(b"Definitely not the correct password", &parsed)
.is_err()
);
Ok(())
}