Message Authentication Code

Sign and verify a message with a HMAC digest

ring ring-crates.io ring-github ring-lib.rs cat-cryptography cat-no-std

An HMAC (Hash-based Message Authentication Code) digest is a type of message authentication code (MAC) that combines a cryptographic hash function with a secret key. It's used to verify both the integrity and authenticity of a message.

Note that HMAC (Hash-based Message Authentication Code) uses a shared secret key between two parties (symmetric cryptography). It provides both integrity and authentication. It cannot be used for non-repudiation (proof of origin by a third party). Since both parties have the key, either could have generated the HMAC.

The following example uses ring::hmac⮳ to creates a ring::signature::Signature⮳ of a string, then verifies the signature is correct.

// An error with absolutely no details (on purpose)
use ring::error::Unspecified;
use ring::hmac;
use ring::rand;
use ring::rand::SecureRandom;

fn main() -> Result<(), Unspecified> {
    // 1. Create a key
    let key;
    {
        let mut key_value = [0u8; 48];
        let rng = rand::SystemRandom::new();
        rng.fill(&mut key_value)?;
        // Construct an HMAC signing key using the given digest algorithm
        // and key value. `key_value`` should be a value generated with
        // a secure random number generator.
        key = hmac::Key::new(hmac::HMAC_SHA256, &key_value);
    }

    // 2. Sign a message
    let message = "Legitimate and important message.";
    let signature = hmac::sign(&key, message.as_bytes());

    // 3. Calculates the HMAC of data using the signing key,
    // and verifies whether the resultant value equals the signature.
    hmac::verify(&key, message.as_bytes(), signature.as_ref())?;
    println!("Message verified.");
    Ok(())
}