Skip to main content

aws_lc_rs/
hmac.rs

1// Copyright 2015-2022 Brian Smith.
2// SPDX-License-Identifier: ISC
3// Modifications copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
4// SPDX-License-Identifier: Apache-2.0 OR ISC
5
6//! HMAC is specified in [RFC 2104].
7//!
8//! After a `Key` is constructed, it can be used for multiple signing or
9//! verification operations. Separating the construction of the key from the
10//! rest of the HMAC operation allows the per-key precomputation to be done
11//! only once, instead of it being done in every HMAC operation.
12//!
13//! Frequently all the data to be signed in a message is available in a single
14//! contiguous piece. In that case, the module-level `sign` function can be
15//! used. Otherwise, if the input is in multiple parts, `Context` should be
16//! used.
17//!
18//! # Examples:
19//!
20//! ## Signing a value and verifying it wasn't tampered with
21//!
22//! ```
23//! use aws_lc_rs::{hmac, rand};
24//!
25//! let rng = rand::SystemRandom::new();
26//! let key = hmac::Key::generate(hmac::HMAC_SHA256, &rng)?;
27//!
28//! let msg = "hello, world";
29//!
30//! let tag = hmac::sign(&key, msg.as_bytes());
31//!
32//! // [We give access to the message to an untrusted party, and they give it
33//! // back to us. We need to verify they didn't tamper with it.]
34//!
35//! hmac::verify(&key, msg.as_bytes(), tag.as_ref())?;
36//!
37//! # Ok::<(), aws_lc_rs::error::Unspecified>(())
38//! ```
39//!
40//! ## Using the one-shot API:
41//!
42//! ```
43//! use aws_lc_rs::rand::SecureRandom;
44//! use aws_lc_rs::{digest, hmac, rand};
45//!
46//! let msg = "hello, world";
47//!
48//! // The sender generates a secure key value and signs the message with it.
49//! // Note that in a real protocol, a key agreement protocol would be used to
50//! // derive `key_value`.
51//! let rng = rand::SystemRandom::new();
52//! let key_value: [u8; digest::SHA256_OUTPUT_LEN] = rand::generate(&rng)?.expose();
53//!
54//! let s_key = hmac::Key::new(hmac::HMAC_SHA256, key_value.as_ref());
55//! let tag = hmac::sign(&s_key, msg.as_bytes());
56//!
57//! // The receiver (somehow!) knows the key value, and uses it to verify the
58//! // integrity of the message.
59//! let v_key = hmac::Key::new(hmac::HMAC_SHA256, key_value.as_ref());
60//! hmac::verify(&v_key, msg.as_bytes(), tag.as_ref())?;
61//!
62//! # Ok::<(), aws_lc_rs::error::Unspecified>(())
63//! ```
64//!
65//! ## Using the multi-part API:
66//! ```
67//! use aws_lc_rs::rand::SecureRandom;
68//! use aws_lc_rs::{digest, hmac, rand};
69//!
70//! let parts = ["hello", ", ", "world"];
71//!
72//! // The sender generates a secure key value and signs the message with it.
73//! // Note that in a real protocol, a key agreement protocol would be used to
74//! // derive `key_value`.
75//! let rng = rand::SystemRandom::new();
76//! let mut key_value: [u8; digest::SHA384_OUTPUT_LEN] = rand::generate(&rng)?.expose();
77//!
78//! let s_key = hmac::Key::new(hmac::HMAC_SHA384, key_value.as_ref());
79//! let mut s_ctx = hmac::Context::with_key(&s_key);
80//! for part in &parts {
81//!     s_ctx.update(part.as_bytes());
82//! }
83//! let tag = s_ctx.sign();
84//!
85//! // The receiver (somehow!) knows the key value, and uses it to verify the
86//! // integrity of the message.
87//! let v_key = hmac::Key::new(hmac::HMAC_SHA384, key_value.as_ref());
88//! let mut msg = Vec::<u8>::new();
89//! for part in &parts {
90//!     msg.extend(part.as_bytes());
91//! }
92//! hmac::verify(&v_key, &msg.as_ref(), tag.as_ref())?;
93//!
94//! # Ok::<(), aws_lc_rs::error::Unspecified>(())
95//! ```
96//! [RFC 2104]: https://tools.ietf.org/html/rfc2104
97
98use crate::aws_lc::{
99    HMAC_CTX_cleanup, HMAC_CTX_copy_ex, HMAC_CTX_init, HMAC_Final, HMAC_Init_ex, HMAC_Update,
100    HMAC_CTX,
101};
102use crate::error::Unspecified;
103use crate::fips::indicator_check;
104use crate::{constant_time, digest, hkdf};
105use core::ffi::c_uint;
106use core::mem::MaybeUninit;
107use core::ptr::null_mut;
108
109/// A deprecated alias for `Tag`.
110#[deprecated(since = "1.0.0", note = "Renamed to `hmac::Tag`.")]
111pub type Signature = Tag;
112/// Renamed to `Context`.
113#[deprecated(since = "1.0.0", note = "Renamed to `hmac::Context`.")]
114pub type SigningContext = Context;
115/// Renamed to `Key`.
116#[deprecated(since = "1.0.0", note = "Renamed to `hmac::Key`.")]
117pub type SigningKey = Key;
118/// Merged into `Key`.
119#[deprecated(
120    since = "1.0.0",
121    note = "Merged into `hmac::Key`, which is used for both signing and verification."
122)]
123pub type VerificationKey = Key;
124
125/// An HMAC algorithm.
126#[derive(Clone, Copy, Debug, PartialEq, Eq)]
127pub struct Algorithm(&'static digest::Algorithm);
128
129impl Algorithm {
130    /// The digest algorithm this HMAC algorithm is based on.
131    #[inline]
132    #[must_use]
133    pub fn digest_algorithm(&self) -> &'static digest::Algorithm {
134        self.0
135    }
136
137    /// The tag length for this HMAC algorithm.
138    #[inline]
139    #[must_use]
140    pub fn tag_len(&self) -> usize {
141        self.digest_algorithm().output_len
142    }
143}
144
145/// HMAC using SHA-1. Obsolete.
146pub const HMAC_SHA1_FOR_LEGACY_USE_ONLY: Algorithm = Algorithm(&digest::SHA1_FOR_LEGACY_USE_ONLY);
147
148/// HMAC using SHA-224.
149pub const HMAC_SHA224: Algorithm = Algorithm(&digest::SHA224);
150
151/// HMAC using SHA-256.
152pub const HMAC_SHA256: Algorithm = Algorithm(&digest::SHA256);
153
154/// HMAC using SHA-384.
155pub const HMAC_SHA384: Algorithm = Algorithm(&digest::SHA384);
156
157/// HMAC using SHA-512.
158pub const HMAC_SHA512: Algorithm = Algorithm(&digest::SHA512);
159
160/// An HMAC tag.
161///
162/// For a given tag `t`, use `t.as_ref()` to get the tag value as a byte slice.
163#[derive(Clone, Copy, Debug)]
164pub struct Tag {
165    msg: [u8; digest::MAX_OUTPUT_LEN],
166    msg_len: usize,
167}
168
169impl AsRef<[u8]> for Tag {
170    #[inline]
171    fn as_ref(&self) -> &[u8] {
172        &self.msg[..self.msg_len]
173    }
174}
175
176struct LcHmacCtx(HMAC_CTX);
177
178impl LcHmacCtx {
179    fn as_mut_ptr(&mut self) -> *mut HMAC_CTX {
180        &mut self.0
181    }
182    fn as_ptr(&self) -> *const HMAC_CTX {
183        &self.0
184    }
185
186    fn try_clone(&self) -> Result<Self, Unspecified> {
187        unsafe {
188            let mut hmac_ctx = MaybeUninit::<HMAC_CTX>::uninit();
189            HMAC_CTX_init(hmac_ctx.as_mut_ptr());
190            let mut hmac_ctx = hmac_ctx.assume_init();
191            if 1 != HMAC_CTX_copy_ex(&mut hmac_ctx, self.as_ptr()) {
192                return Err(Unspecified);
193            }
194            Ok(LcHmacCtx(hmac_ctx))
195        }
196    }
197}
198unsafe impl Send for LcHmacCtx {}
199
200impl Drop for LcHmacCtx {
201    fn drop(&mut self) {
202        unsafe { HMAC_CTX_cleanup(self.as_mut_ptr()) }
203    }
204}
205
206impl Clone for LcHmacCtx {
207    fn clone(&self) -> Self {
208        self.try_clone().expect("Unable to clone LcHmacCtx")
209    }
210}
211
212/// A key to use for HMAC signing.
213//
214// # FIPS
215// Use this type with one of the following algorithms:
216// * `HMAC_SHA1_FOR_LEGACY_USE_ONLY`
217// * `HMAC_SHA224`
218// * `HMAC_SHA256`
219// * `HMAC_SHA384`
220// * `HMAC_SHA512`
221#[derive(Clone)]
222pub struct Key {
223    pub(crate) algorithm: Algorithm,
224    ctx: LcHmacCtx,
225}
226
227unsafe impl Send for Key {}
228// All uses of *mut HMAC_CTX require the creation of a Context, which will clone the Key.
229unsafe impl Sync for Key {}
230
231#[allow(clippy::missing_fields_in_debug)]
232impl core::fmt::Debug for Key {
233    fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
234        f.debug_struct("Key")
235            .field("algorithm", &self.algorithm.digest_algorithm())
236            .finish()
237    }
238}
239
240impl Key {
241    /// Generate an HMAC signing key using the given digest algorithm with a
242    /// random value generated from `rng`.
243    ///
244    /// The key will be `digest_alg.output_len` bytes long, based on the
245    /// recommendation in [RFC 2104 Section 3].
246    ///
247    /// [RFC 2104 Section 3]: https://tools.ietf.org/html/rfc2104#section-3
248    ///
249    //
250    // # FIPS
251    // Use this function with one of the following algorithms:
252    // * `HMAC_SHA1_FOR_LEGACY_USE_ONLY`
253    // * `HMAC_SHA224`
254    // * `HMAC_SHA256`
255    // * `HMAC_SHA384`
256    // * `HMAC_SHA512`
257    //
258    /// # Errors
259    /// `error::Unspecified` is the `rng` fails.
260    pub fn generate(
261        algorithm: Algorithm,
262        rng: &dyn crate::rand::SecureRandom,
263    ) -> Result<Self, Unspecified> {
264        Self::construct(algorithm, |buf| rng.fill(buf))
265    }
266
267    fn construct<F>(algorithm: Algorithm, fill: F) -> Result<Self, Unspecified>
268    where
269        F: FnOnce(&mut [u8]) -> Result<(), Unspecified>,
270    {
271        let mut key_bytes = [0; digest::MAX_OUTPUT_LEN];
272        let key_bytes = &mut key_bytes[..algorithm.tag_len()];
273        fill(key_bytes)?;
274        Ok(Self::new(algorithm, key_bytes))
275    }
276
277    /// Construct an HMAC signing key using the given digest algorithm and key
278    /// value.
279    ///
280    /// `key_value` should be a value generated using a secure random number
281    /// generator (e.g. the `key_value` output by
282    /// `SealingKey::generate_serializable()`) or derived from a random key by
283    /// a key derivation function (e.g. `aws_lc_rs::hkdf`). In particular,
284    /// `key_value` shouldn't be a password.
285    ///
286    /// As specified in RFC 2104, if `key_value` is shorter than the digest
287    /// algorithm's block length (as returned by `digest::Algorithm::block_len`,
288    /// not the digest length returned by `digest::Algorithm::output_len`) then
289    /// it will be padded with zeros. Similarly, if it is longer than the block
290    /// length then it will be compressed using the digest algorithm.
291    ///
292    /// You should not use keys larger than the `digest_alg.block_len` because
293    /// the truncation described above reduces their strength to only
294    /// `digest_alg.output_len * 8` bits.
295    ///
296    /// # Panics
297    /// Panics if the HMAC context cannot be constructed
298    #[inline]
299    #[must_use]
300    pub fn new(algorithm: Algorithm, key_value: &[u8]) -> Self {
301        Key::try_new(algorithm, key_value).expect("Unable to create HmacContext")
302    }
303
304    fn try_new(algorithm: Algorithm, key_value: &[u8]) -> Result<Self, Unspecified> {
305        unsafe {
306            let mut ctx = MaybeUninit::<HMAC_CTX>::uninit();
307            HMAC_CTX_init(ctx.as_mut_ptr());
308            let evp_md_type = digest::match_digest_type(&algorithm.digest_algorithm().id);
309            if 1 != HMAC_Init_ex(
310                ctx.as_mut_ptr(),
311                key_value.as_ptr().cast(),
312                key_value.len(),
313                evp_md_type.as_const_ptr(),
314                null_mut(),
315            ) {
316                return Err(Unspecified);
317            }
318            let result = Self {
319                algorithm,
320                ctx: LcHmacCtx(ctx.assume_init()),
321            };
322            Ok(result)
323        }
324    }
325
326    unsafe fn get_hmac_ctx_ptr(&mut self) -> *mut HMAC_CTX {
327        self.ctx.as_mut_ptr()
328    }
329
330    /// The digest algorithm for the key.
331    #[inline]
332    #[must_use]
333    pub fn algorithm(&self) -> Algorithm {
334        Algorithm(self.algorithm.digest_algorithm())
335    }
336}
337
338impl hkdf::KeyType for Algorithm {
339    #[inline]
340    fn len(&self) -> usize {
341        self.tag_len()
342    }
343}
344
345impl From<hkdf::Okm<'_, Algorithm>> for Key {
346    fn from(okm: hkdf::Okm<Algorithm>) -> Self {
347        Self::construct(*okm.len(), |buf| okm.fill(buf)).unwrap()
348    }
349}
350
351/// A context for multi-step (Init-Update-Finish) HMAC signing.
352///
353/// Use `sign` for single-step HMAC signing.
354pub struct Context {
355    key: Key,
356}
357
358impl Clone for Context {
359    fn clone(&self) -> Self {
360        Self {
361            key: self.key.clone(),
362        }
363    }
364}
365
366unsafe impl Send for Context {}
367
368impl core::fmt::Debug for Context {
369    fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
370        f.debug_struct("Context")
371            .field("algorithm", &self.key.algorithm.digest_algorithm())
372            .finish()
373    }
374}
375
376impl Context {
377    /// Constructs a new HMAC signing context using the given digest algorithm
378    /// and key.
379    #[inline]
380    #[must_use]
381    pub fn with_key(signing_key: &Key) -> Self {
382        Self {
383            key: signing_key.clone(),
384        }
385    }
386
387    /// Updates the HMAC with all the data in `data`. `update` may be called
388    /// zero or more times until `finish` is called.
389    ///
390    /// # Panics
391    /// Panics if the HMAC cannot be updated
392    #[inline]
393    pub fn update(&mut self, data: &[u8]) {
394        Self::try_update(self, data).expect("HMAC_Update failed");
395    }
396
397    #[inline]
398    fn try_update(&mut self, data: &[u8]) -> Result<(), Unspecified> {
399        unsafe {
400            if 1 != HMAC_Update(self.key.get_hmac_ctx_ptr(), data.as_ptr(), data.len()) {
401                return Err(Unspecified);
402            }
403        }
404        Ok(())
405    }
406
407    /// Finalizes the HMAC calculation and returns the HMAC value. `sign`
408    /// consumes the context so it cannot be (mis-)used after `sign` has been
409    /// called.
410    ///
411    /// It is generally not safe to implement HMAC verification by comparing
412    /// the return value of `sign` to a tag. Use `verify` for verification
413    /// instead.
414    ///
415    // # FIPS
416    // Use this method with one of the following algorithms:
417    // * `HMAC_SHA1_FOR_LEGACY_USE_ONLY`
418    // * `HMAC_SHA224`
419    // * `HMAC_SHA256`
420    // * `HMAC_SHA384`
421    // * `HMAC_SHA512`
422    //
423    /// # Panics
424    /// Panics if the HMAC calculation cannot be finalized
425    #[inline]
426    #[must_use]
427    pub fn sign(self) -> Tag {
428        Self::try_sign(self).expect("HMAC_Final failed")
429    }
430    #[inline]
431    fn try_sign(mut self) -> Result<Tag, Unspecified> {
432        let mut output = [0u8; digest::MAX_OUTPUT_LEN];
433        let msg_len = {
434            let result = internal_sign(&mut self, &mut output)?;
435            result.len()
436        };
437        Ok(Tag {
438            msg: output,
439            msg_len,
440        })
441    }
442}
443
444#[inline]
445pub(crate) fn internal_sign<'in_out>(
446    ctx: &mut Context,
447    output: &'in_out mut [u8],
448) -> Result<&'in_out mut [u8], Unspecified> {
449    let tag_len = ctx.key.algorithm().tag_len();
450    if output.len() < tag_len {
451        return Err(Unspecified);
452    }
453
454    let mut out_len = MaybeUninit::<c_uint>::uninit();
455
456    if 1 != indicator_check!(unsafe {
457        HMAC_Final(
458            ctx.key.get_hmac_ctx_ptr(),
459            output.as_mut_ptr(),
460            out_len.as_mut_ptr(),
461        )
462    }) {
463        return Err(Unspecified);
464    }
465    let actual_len = unsafe { out_len.assume_init() } as usize;
466
467    debug_assert!(
468        actual_len == tag_len,
469        "HMAC tag length {actual_len} does not match expected length {tag_len}"
470    );
471
472    Ok(&mut output[0..tag_len])
473}
474
475/// Calculates the HMAC of `data` using the key `key` in one step.
476///
477/// Use `Context` to calculate HMACs where the input is in multiple parts.
478///
479/// It is generally not safe to implement HMAC verification by comparing the
480/// return value of `sign` to a tag. Use `verify` for verification instead.
481//
482// # FIPS
483// Use this function with one of the following algorithms:
484// * `HMAC_SHA1_FOR_LEGACY_USE_ONLY`
485// * `HMAC_SHA224`
486// * `HMAC_SHA256`
487// * `HMAC_SHA384`
488// * `HMAC_SHA512`
489#[inline]
490#[must_use]
491pub fn sign(key: &Key, data: &[u8]) -> Tag {
492    let mut ctx = Context::with_key(key);
493    ctx.update(data);
494    ctx.sign()
495}
496
497/// Calculates the HMAC of `data` using the key `key` in one step,
498/// writing the result into the provided `output` buffer.
499///
500/// The `output` buffer must be at least as large as the algorithm's
501/// tag length (i.e., `key.algorithm().tag_len()`). The returned slice will be a
502/// sub-slice of `output` containing exactly the tag bytes.
503///
504/// It is generally not safe to implement HMAC verification by comparing the
505/// return value of `sign_to_buffer` to a tag. Use `verify` for verification instead.
506//
507// # FIPS
508// Use this function with one of the following algorithms:
509// * `HMAC_SHA1_FOR_LEGACY_USE_ONLY`
510// * `HMAC_SHA224`
511// * `HMAC_SHA256`
512// * `HMAC_SHA384`
513// * `HMAC_SHA512`
514//
515/// # Errors
516/// `error::Unspecified` if `output` is too small or if the HMAC operation fails.
517#[inline]
518pub fn sign_to_buffer<'out>(
519    key: &Key,
520    data: &[u8],
521    output: &'out mut [u8],
522) -> Result<&'out mut [u8], Unspecified> {
523    let mut ctx = Context::with_key(key);
524    ctx.update(data);
525
526    internal_sign(&mut ctx, output)
527}
528
529/// Calculates the HMAC of `data` using the signing key `key`, and verifies
530/// whether the resultant value equals `tag`, in one step.
531///
532/// This is logically equivalent to, but more efficient than, constructing a
533/// `Key` with the same value as `key` and then using `verify`.
534///
535/// The verification will be done in constant time to prevent timing attacks.
536///
537/// # Errors
538/// `error::Unspecified` if the inputs are not verified.
539//
540// # FIPS
541// Use this function with one of the following algorithms:
542// * `HMAC_SHA1_FOR_LEGACY_USE_ONLY`
543// * `HMAC_SHA224`
544// * `HMAC_SHA256`
545// * `HMAC_SHA384`
546// * `HMAC_SHA512`
547#[inline]
548pub fn verify(key: &Key, data: &[u8], tag: &[u8]) -> Result<(), Unspecified> {
549    constant_time::verify_slices_are_equal(sign(key, data).as_ref(), tag)
550}
551
552#[cfg(test)]
553mod tests {
554    use crate::{hmac, rand};
555
556    #[cfg(feature = "fips")]
557    mod fips;
558
559    #[test]
560    fn hmac_algorithm_properties() {
561        assert_eq!(hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY.tag_len(), 20);
562        assert_eq!(hmac::HMAC_SHA224.tag_len(), 28);
563        assert_eq!(hmac::HMAC_SHA256.tag_len(), 32);
564        assert_eq!(hmac::HMAC_SHA384.tag_len(), 48);
565        assert_eq!(hmac::HMAC_SHA512.tag_len(), 64);
566    }
567
568    // Make sure that internal_sign properly rejects too small buffers
569    // (and does not corrupt memory by buffer overflow)
570    #[test]
571    fn hmac_internal_sign_too_small_buffer() {
572        let rng = rand::SystemRandom::new();
573
574        for algorithm in &[
575            hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY,
576            hmac::HMAC_SHA224,
577            hmac::HMAC_SHA256,
578            hmac::HMAC_SHA384,
579            hmac::HMAC_SHA512,
580        ] {
581            let key = hmac::Key::generate(*algorithm, &rng).unwrap();
582            let data = b"hello, world";
583
584            // Buffer one byte too small should fail
585            let mut small_buf = vec![0u8; algorithm.tag_len() - 1];
586            let mut ctx = hmac::Context::with_key(&key);
587            ctx.update(data);
588            assert!(super::internal_sign(&mut ctx, &mut small_buf).is_err());
589
590            // Empty buffer should fail
591            let mut empty_buf = vec![];
592            let mut ctx = hmac::Context::with_key(&key);
593            ctx.update(data);
594            assert!(super::internal_sign(&mut ctx, &mut empty_buf).is_err());
595        }
596    }
597
598    // Make sure that `Key::generate` and `verify_with_own_key` aren't
599    // completely wacky.
600    #[test]
601    pub fn hmac_signing_key_coverage() {
602        const HELLO_WORLD_GOOD: &[u8] = b"hello, world";
603        const HELLO_WORLD_BAD: &[u8] = b"hello, worle";
604
605        let rng = rand::SystemRandom::new();
606
607        for algorithm in &[
608            hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY,
609            hmac::HMAC_SHA224,
610            hmac::HMAC_SHA256,
611            hmac::HMAC_SHA384,
612            hmac::HMAC_SHA512,
613        ] {
614            let key = hmac::Key::generate(*algorithm, &rng).unwrap();
615            let tag = hmac::sign(&key, HELLO_WORLD_GOOD);
616            println!("{key:?}");
617            assert!(hmac::verify(&key, HELLO_WORLD_GOOD, tag.as_ref()).is_ok());
618            assert!(hmac::verify(&key, HELLO_WORLD_BAD, tag.as_ref()).is_err());
619        }
620    }
621
622    #[test]
623    fn hmac_coverage() {
624        // Something would have gone horribly wrong for this to not pass, but we test this so our
625        // coverage reports will look better.
626        assert_ne!(hmac::HMAC_SHA256, hmac::HMAC_SHA384);
627
628        for &alg in &[
629            hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY,
630            hmac::HMAC_SHA224,
631            hmac::HMAC_SHA256,
632            hmac::HMAC_SHA384,
633            hmac::HMAC_SHA512,
634        ] {
635            // Clone after updating context with message, then check if the final Tag is the same.
636            let key = hmac::Key::new(alg, &[0; 32]);
637            let mut ctx = hmac::Context::with_key(&key);
638            ctx.update(b"hello, world");
639            let ctx_clone = ctx.clone();
640
641            let orig_tag = ctx.sign();
642            let clone_tag = ctx_clone.sign();
643            assert_eq!(orig_tag.as_ref(), clone_tag.as_ref());
644            assert_eq!(orig_tag.clone().as_ref(), clone_tag.as_ref());
645        }
646    }
647
648    #[test]
649    fn hmac_sign_to_buffer_test() {
650        let rng = rand::SystemRandom::new();
651
652        for &algorithm in &[
653            hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY,
654            hmac::HMAC_SHA224,
655            hmac::HMAC_SHA256,
656            hmac::HMAC_SHA384,
657            hmac::HMAC_SHA512,
658        ] {
659            let key = hmac::Key::generate(algorithm, &rng).unwrap();
660            let data = b"hello, world";
661            let tag_len = algorithm.tag_len();
662
663            // Test with exact size buffer
664            let mut output = vec![0u8; tag_len];
665            let result = hmac::sign_to_buffer(&key, data, &mut output).unwrap();
666            assert_eq!(result.len(), tag_len);
667
668            // Verify the returned tag matches sign() and passes verify()
669            let tag = hmac::sign(&key, data);
670            assert_eq!(result, tag.as_ref());
671            assert!(hmac::verify(&key, data, result).is_ok());
672
673            // Verify the output buffer also matches sign() and passes verify()
674            assert_eq!(output.as_slice(), tag.as_ref());
675            assert!(hmac::verify(&key, data, output.as_slice()).is_ok());
676
677            // Test with larger buffer
678            let mut large_output = vec![0u8; tag_len + 10];
679            let result2 = hmac::sign_to_buffer(&key, data, &mut large_output).unwrap();
680            assert_eq!(result2.len(), tag_len);
681            assert_eq!(result2, tag.as_ref());
682            assert!(hmac::verify(&key, data, result2).is_ok());
683            assert_eq!(&large_output[0..tag_len], tag.as_ref());
684        }
685    }
686
687    #[test]
688    fn hmac_sign_to_buffer_too_small_test() {
689        let key = hmac::Key::new(hmac::HMAC_SHA256, &[0; 32]);
690        let data = b"hello";
691
692        // Buffer too small should fail
693        let mut small_buffer = vec![0u8; hmac::HMAC_SHA256.tag_len() - 1];
694        assert!(hmac::sign_to_buffer(&key, data, &mut small_buffer).is_err());
695
696        // Empty buffer should fail
697        let mut empty_buffer = vec![];
698        assert!(hmac::sign_to_buffer(&key, data, &mut empty_buffer).is_err());
699    }
700}