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