hmac/lib.rs
1//! Generic implementation of Hash-based Message Authentication Code (HMAC).
2//!
3//! To use it you will need a cryptographic hash function implementation which
4//! implements the [`digest`] crate traits. You can find compatible crates
5//! (e.g. [`sha2`]) in the [`RustCrypto/hashes`] repository.
6//!
7//! This crate provides two HMAC implementation [`Hmac`] and [`SimpleHmac`].
8//! The first one is a buffered wrapper around block-level [`HmacCore`].
9//! Internally it uses efficient state representation, but works only with
10//! hash functions which expose block-level API and consume blocks eagerly
11//! (e.g. it will not work with the BLAKE2 family of hash functions).
12//! On the other hand, [`SimpleHmac`] is a bit less efficient memory-wise,
13//! but works with all hash functions which implement the [`Digest`] trait.
14//!
15//! # Examples
16//! Let us demonstrate how to use HMAC using the SHA-256 hash function.
17//!
18//! In the following examples [`Hmac`] is interchangeable with [`SimpleHmac`].
19//!
20//! To get authentication code:
21//!
22//! ```rust
23//! use sha2::Sha256;
24//! use hmac::{Hmac, Mac};
25//! use hex_literal::hex;
26//!
27//! // Create alias for HMAC-SHA256
28//! type HmacSha256 = Hmac<Sha256>;
29//!
30//! let mut mac = HmacSha256::new_from_slice(b"my secret and secure key")
31//! .expect("HMAC can take key of any size");
32//! mac.update(b"input message");
33//!
34//! // `result` has type `CtOutput` which is a thin wrapper around array of
35//! // bytes for providing constant time equality check
36//! let result = mac.finalize();
37//! // To get underlying array use `into_bytes`, but be careful, since
38//! // incorrect use of the code value may permit timing attacks which defeats
39//! // the security provided by the `CtOutput`
40//! let code_bytes = result.into_bytes();
41//! let expected = hex!("
42//! 97d2a569059bbcd8ead4444ff99071f4
43//! c01d005bcefe0d3567e1be628e5fdcd9
44//! ");
45//! assert_eq!(code_bytes[..], expected[..]);
46//! ```
47//!
48//! To verify the message:
49//!
50//! ```rust
51//! # use sha2::Sha256;
52//! # use hmac::{Hmac, Mac};
53//! # use hex_literal::hex;
54//! # type HmacSha256 = Hmac<Sha256>;
55//! let mut mac = HmacSha256::new_from_slice(b"my secret and secure key")
56//! .expect("HMAC can take key of any size");
57//!
58//! mac.update(b"input message");
59//!
60//! let code_bytes = hex!("
61//! 97d2a569059bbcd8ead4444ff99071f4
62//! c01d005bcefe0d3567e1be628e5fdcd9
63//! ");
64//! // `verify_slice` will return `Ok(())` if code is correct, `Err(MacError)` otherwise
65//! mac.verify_slice(&code_bytes[..]).unwrap();
66//! ```
67//!
68//! # Block and input sizes
69//! Usually it is assumed that block size is larger than output size. Due to the
70//! generic nature of the implementation, this edge case must be handled as well
71//! to remove potential panic. This is done by truncating hash output to the hash
72//! block size if needed.
73//!
74//! [`digest`]: https://docs.rs/digest
75//! [`sha2`]: https://docs.rs/sha2
76//! [`RustCrypto/hashes`]: https://github.com/RustCrypto/hashes
77
78#![no_std]
79#![doc(
80 html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/26acc39f/logo.svg",
81 html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/26acc39f/logo.svg",
82 html_root_url = "https://docs.rs/hmac/0.12.1"
83)]
84#![forbid(unsafe_code)]
85#![cfg_attr(docsrs, feature(doc_cfg))]
86#![warn(missing_docs, rust_2018_idioms)]
87
88#[cfg(feature = "std")]
89extern crate std;
90
91pub use digest;
92pub use digest::Mac;
93
94use digest::{
95 core_api::{Block, BlockSizeUser},
96 Digest,
97};
98
99mod optim;
100mod simple;
101
102pub use optim::{Hmac, HmacCore};
103pub use simple::SimpleHmac;
104
105const IPAD: u8 = 0x36;
106const OPAD: u8 = 0x5C;
107
108fn get_der_key<D: Digest + BlockSizeUser>(key: &[u8]) -> Block<D> {
109 let mut der_key = Block::<D>::default();
110 // The key that HMAC processes must be the same as the block size of the
111 // underlying hash function. If the provided key is smaller than that,
112 // we just pad it with zeros. If its larger, we hash it and then pad it
113 // with zeros.
114 if key.len() <= der_key.len() {
115 der_key[..key.len()].copy_from_slice(key);
116 } else {
117 let hash = D::digest(key);
118 // All commonly used hash functions have block size bigger
119 // than output hash size, but to be extra rigorous we
120 // handle the potential uncommon cases as well.
121 // The condition is calcualted at compile time, so this
122 // branch gets removed from the final binary.
123 if hash.len() <= der_key.len() {
124 der_key[..hash.len()].copy_from_slice(&hash);
125 } else {
126 let n = der_key.len();
127 der_key.copy_from_slice(&hash[..n]);
128 }
129 }
130 der_key
131}