Crate hmac[][src]

Generic implementation of Hash-based Message Authentication Code (HMAC).

To use it you’ll need a cryptographic hash function implementation from RustCrypto project. You can either import specific crate (e.g. sha2), or meta-crate crypto-hashes which reexport all related crates.

Usage

Let us demonstrate how to use HMAC using SHA256 as an example.

To get the authentication code:

use sha2::Sha256;
use hmac::{Hmac, Mac, NewMac};

// Create alias for HMAC-SHA256
type HmacSha256 = Hmac<Sha256>;

// Create HMAC-SHA256 instance which implements `Mac` trait
let mut mac = HmacSha256::new_from_slice(b"my secret and secure key")
    .expect("HMAC can take key of any size");
mac.update(b"input message");

// `result` has type `Output` which is a thin wrapper around array of
// bytes for providing constant time equality check
let result = mac.finalize();
// To get underlying array use `into_bytes` method, but be careful, since
// incorrect use of the code value may permit timing attacks which defeat
// the security provided by the `Output`
let code_bytes = result.into_bytes();

To verify the message:

let mut mac = HmacSha256::new_from_slice(b"my secret and secure key")
    .expect("HMAC can take key of any size");

mac.update(b"input message");

// `verify` will return `Ok(())` if code is correct, `Err(MacError)` otherwise
mac.verify(&code_bytes).unwrap();

Block and input sizes

Usually it is assumed that block size is larger than output size, due to the generic nature of the implementation this edge case must be handled as well to remove potential panic scenario. This is done by truncating hash output to the hash block size if needed.

Re-exports

pub use crypto_mac;
pub use digest;

Structs

Hmac

The Hmac struct represents an HMAC using a given hash function D.

Traits

Mac

The Mac trait defines methods for a Message Authentication algorithm.

NewMac

Instantiate a Mac algorithm.