Skip to content

Security crates

Secrets, hashing, HMAC, password hashing, JWTs, and TLS in Rust on aws-lc-rs and rustls.

Secrets handling, cryptographic primitives, tokens, and TLS. Everything on this page runs on aws-lc-rs; the overview lists the feature flag each crate needs to stay on it.

Secrets

Crate Use Links
secrecy Redacted, explicit-access secret types crates.io · lib.rs · GitHub
zeroize Clear secret memory on drop crates.io · lib.rs · GitHub

Wrap every credential in configuration with SecretString or SecretBox<T>. Debug prints [REDACTED], so the config struct can derive Debug and appear in logs and tracing fields safely. There is no Serialize impl, so a secret cannot leak into a JSON response or a config dump. Reading the value requires expose_secret(), which makes each use greppable in review. Deserializing needs the serde feature.

use secrecy::{ExposeSecret, SecretString};
use serde::Deserialize;

#[derive(Debug, Deserialize)]
pub struct Config {
    pub listen_addr: std::net::SocketAddr,
    pub database_url: SecretString,
    pub api_token: SecretString,
}

let pool = sqlx::PgPool::connect(config.database_url.expose_secret()).await?;

Call expose_secret() at the last moment and pass the &str directly into the consuming call. Binding it to a local String creates a copy that is neither redacted nor zeroed.

secrecy zeroizes its contents on drop through zeroize. Derive ZeroizeOnDrop directly on owned key material that does not fit a SecretBox:

use zeroize::{Zeroize, ZeroizeOnDrop};

#[derive(Zeroize, ZeroizeOnDrop)]
pub struct SessionKey {
    bytes: [u8; 32],
}

Zeroizing clears only the memory the value occupies when it drops. A move of a stack value, or a Vec or String that reallocates as it grows, can leave earlier copies behind. SecretBox keeps the value on the heap at a fixed address, which is why it wraps a Box. Treat zeroization as defense in depth against memory disclosure, not a guarantee.

Cryptography

Crate Use Links
aws-lc-rs Hashes, HMAC, AEAD, signatures, HKDF, RNG crates.io · lib.rs · GitHub
argon2 Password hashing crates.io · lib.rs · GitHub

aws-lc-rs covers every general-purpose primitive with an API modeled on ring. Every other crate here uses it as its backend; see One crypto backend.

use aws_lc_rs::{constant_time, digest, hmac, rand};

// SHA-256
let hash = digest::digest(&digest::SHA256, body);

// HMAC-SHA256: sign, then verify in constant time
let key = hmac::Key::new(hmac::HMAC_SHA256, secret);
let tag = hmac::sign(&key, body);
hmac::verify(&key, body, received_tag)?;

// Random bytes from the OS-seeded DRBG
let mut token = [0u8; 32];
rand::fill(&mut token)?;

// Constant-time comparison of two secrets
constant_time::verify_slices_are_equal(expected, presented)?;

Compare MACs, API keys, and session tokens with hmac::verify or constant_time::verify_slices_are_equal. A plain == on &[u8] returns at the first differing byte.

aws-lc-rs offers PBKDF2 but no memory-hard password hash. Use argon2: the defaults are Argon2id with OWASP-recommended parameters, and hash_password generates the salt and returns a PHC string that embeds the algorithm, parameters, and salt.

use argon2::{
    password_hash::{phc::PasswordHash, PasswordHasher, PasswordVerifier},
    Argon2,
};

let phc = Argon2::default().hash_password(password.as_bytes())?.to_string();

// Verification reads parameters from the stored string, so raising
// the cost later does not invalidate existing hashes.
let parsed = PasswordHash::new(&phc)?;
Argon2::default().verify_password(password.as_bytes(), &parsed)?;

aws-lc-rs builds AWS-LC from C source, so every build host and cross-compilation toolchain needs a C/C++ compiler for the target. The default build uses pregenerated bindings and needs nothing else. The fips feature also requires CMake and Go.

JWTs

Crate Use Links
jsonwebtoken Sign and verify JWTs, parse JWKS crates.io · lib.rs · GitHub

jsonwebtoken 12 ships no crypto by default. Enable exactly one of aws_lc_rs or rust_crypto; with neither, or with both after feature unification, the first encode or decode panics. Choose aws_lc_rs to share the backend with rustls.

Claim, algorithm, and lifetime choices are covered in Authentication. The Rust side is mostly about configuring Validation so those choices are enforced.

Verifying

use jsonwebtoken::{decode, decode_header, jwk::JwkSet, Algorithm, DecodingKey, Validation};
use serde::Deserialize;

#[derive(Debug, Deserialize)]
pub struct Claims {
    pub sub: String,
    pub exp: i64,
    pub iat: i64,
    pub scope: String,
}

pub struct Verifier {
    jwks: JwkSet,
    validation: Validation,
}

impl Verifier {
    pub fn new(jwks: JwkSet, issuer: &str, audience: &str) -> Self {
        // Pin the algorithm from configuration. Never trust the token's own `alg` header.
        let mut validation = Validation::new(Algorithm::ES256);
        validation.set_issuer(&[issuer]);
        validation.set_audience(&[audience]);
        validation.set_required_spec_claims(&["exp", "iss", "aud", "sub"]);
        validation.leeway = 30;
        Self { jwks, validation }
    }

    pub fn verify(&self, token: &str) -> Result<Claims, AuthError> {
        let kid = decode_header(token)?.kid.ok_or(AuthError::MissingKid)?;
        let jwk = self.jwks.find(&kid).ok_or(AuthError::UnknownKid)?;
        let key = DecodingKey::from_jwk(jwk)?;
        Ok(decode::<Claims>(token, &key, &self.validation)?.claims)
    }
}

#[derive(Debug, thiserror::Error)]
pub enum AuthError {
    #[error("token has no kid")]
    MissingKid,
    #[error("no key for kid")]
    UnknownKid,
    #[error(transparent)]
    Jwt(#[from] jsonwebtoken::errors::Error),
}

By default Validation requires and checks only exp, with 60 seconds of leeway. iss is not checked unless set_issuer is called, so a token from any issuer whose key is in the JWKS verifies. aud is checked against set_audience, and a token with no aud passes unless aud is in the required claims. nbf is ignored unless validate_nbf is set. Every AuthError maps to a 401.

JwkSet deserializes directly from the issuer’s /.well-known/jwks.json with serde_json. Cache it, and refetch when a kid is unknown, rate-limited so a stream of forged kid values cannot turn into a stream of fetches to the issuer.

Signing

use jsonwebtoken::{encode, Algorithm, EncodingKey, Header};
use serde::Serialize;

#[derive(Serialize)]
struct AccessClaims<'a> {
    iss: &'a str,
    aud: &'a str,
    sub: &'a str,
    iat: i64,
    exp: i64,
    scope: &'a str,
}

fn issue(key: &EncodingKey, kid: &str, user_id: &str, scope: &str) -> jsonwebtoken::errors::Result<String> {
    let now = jiff::Timestamp::now().as_second();
    let claims = AccessClaims {
        iss: "https://auth.example.com",
        aud: "https://api.example.com",
        sub: user_id,
        iat: now,
        exp: now + 15 * 60,
        scope,
    };

    let mut header = Header::new(Algorithm::ES256);
    header.kid = Some(kid.to_owned());
    encode(&header, &claims, key)
}

Load the key once at startup with EncodingKey::from_ec_pem, which expects a PKCS#8 PEM (-----BEGIN PRIVATE KEY-----). Always set kid: it is what lets verifiers pick the right key while two keys overlap during rotation.

TLS

Crate Use Links
rustls TLS client and server crates.io · lib.rs · GitHub
tokio-rustls Async TLS streams on Tokio crates.io · lib.rs · GitHub
rustls-pki-types Certificate and key types, PEM parsing crates.io · lib.rs · GitHub
webpki-roots Bundled Mozilla root store crates.io · lib.rs · GitHub
rustls-native-certs Operating system root store crates.io · lib.rs · GitHub
rcgen X.509 certificate generation crates.io · lib.rs · GitHub

Crypto provider

rustls 0.23 selects aws-lc-rs by default. If any crate in the dependency tree also enables the ring feature on rustls, it cannot choose and panics the first time a config is built. Install the provider as the first line of main so the choice never depends on feature unification:

rustls::crypto::aws_lc_rs::default_provider()
    .install_default()
    .expect("rustls crypto provider already installed");

cargo tree -i ring shows which dependency pulls in ring. rcgen enables it by default; the combined Cargo.toml turns it off.

Server

rustls-pki-types is re-exported as rustls::pki_types and parses PEM directly; no separate PEM crate is needed.

use anyhow::Context;
use rustls::pki_types::{pem::PemObject, CertificateDer, PrivateKeyDer};
use std::sync::Arc;
use tokio_rustls::TlsAcceptor;

fn tls_acceptor(cert_path: &str, key_path: &str) -> anyhow::Result<TlsAcceptor> {
    let certs = CertificateDer::pem_file_iter(cert_path)?
        .collect::<Result<Vec<_>, _>>()
        .context("reading certificate chain")?;
    let key = PrivateKeyDer::from_pem_file(key_path).context("reading private key")?;

    let mut config = rustls::ServerConfig::builder()
        .with_no_client_auth()
        .with_single_cert(certs, key)?;
    config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];

    Ok(TlsAcceptor::from(Arc::new(config)))
}

The certificate file must contain the full chain, leaf first. rustls does not fetch intermediates.

Client

let roots = rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());

let config = rustls::ClientConfig::builder()
    .with_root_certificates(roots)
    .with_no_client_auth();

webpki-roots compiles Mozilla’s root list into the binary, so it works in scratch and distroless images with no CA bundle; updating it means a rebuild. Use rustls-native-certs when operators must be able to add a private CA through the system trust store. reqwest uses the platform verifier by default and accepts a prebuilt ClientConfig through tls_backend_preconfigured; see HTTP client.

Test certificates

let rcgen::CertifiedKey { cert, signing_key } =
    rcgen::generate_simple_self_signed(vec!["localhost".to_string()])?;

let cert_pem = cert.pem();
let key_pem = signing_key.serialize_pem();

Generate certificates in the test rather than committing PEM files, which keeps private keys out of the repository and removes expiry-driven test failures.

Type to search…

↑↓ navigate↵ selectEsc close