wolfcrypt-ring-compat 1.16.5

wolfcrypt-ring-compat is a cryptographic library using wolfSSL for its cryptographic operations. This library strives to be API-compatible with the popular Rust library named ring.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0 OR ISC

//! CMAC is specified in [RFC 4493] and [NIST SP 800-38B].
//!
//! After a `Key` is constructed, it can be used for multiple signing or
//! verification operations. Separating the construction of the key from the
//! rest of the CMAC operation allows the per-key precomputation to be done
//! only once, instead of it being done in every CMAC operation.
//!
//! Frequently all the data to be signed in a message is available in a single
//! contiguous piece. In that case, the module-level `sign` function can be
//! used. Otherwise, if the input is in multiple parts, `Context` should be
//! used.
//!
//! # Examples:
//!
//! ## Signing a value and verifying it wasn't tampered with
//!
//! ```
//! use ring::cmac;
//!
//! let key = cmac::Key::generate(cmac::AES_128)?;
//!
//! let msg = "hello, world";
//!
//! let tag = cmac::sign(&key, msg.as_bytes())?;
//!
//! // [We give access to the message to an untrusted party, and they give it
//! // back to us. We need to verify they didn't tamper with it.]
//!
//! cmac::verify(&key, msg.as_bytes(), tag.as_ref())?;
//!
//! # Ok::<(), ring::error::Unspecified>(())
//! ```
//!
//! ## Using the one-shot API:
//!
//! ```
//! use ring::{cmac, rand};
//!
//! let msg = "hello, world";
//!
//! // The sender generates a secure key value and signs the message with it.
//! // Note that in a real protocol, a key agreement protocol would be used to
//! // derive `key_value`.
//! let rng = rand::SystemRandom::new();
//! let key_value: [u8; 16] = rand::generate(&rng)?.expose();
//!
//! let s_key = cmac::Key::new(cmac::AES_128, key_value.as_ref())?;
//! let tag = cmac::sign(&s_key, msg.as_bytes())?;
//!
//! // The receiver (somehow!) knows the key value, and uses it to verify the
//! // integrity of the message.
//! let v_key = cmac::Key::new(cmac::AES_128, key_value.as_ref())?;
//! cmac::verify(&v_key, msg.as_bytes(), tag.as_ref())?;
//!
//! # Ok::<(), ring::error::Unspecified>(())
//! ```
//!
//! ## Using the multi-part API:
//! ```
//! use ring::{cmac, rand};
//!
//! let parts = ["hello", ", ", "world"];
//!
//! // The sender generates a secure key value and signs the message with it.
//! // Note that in a real protocol, a key agreement protocol would be used to
//! // derive `key_value`.
//! let rng = rand::SystemRandom::new();
//! let key_value: [u8; 32] = rand::generate(&rng)?.expose();
//!
//! let s_key = cmac::Key::new(cmac::AES_256, key_value.as_ref())?;
//! let mut s_ctx = cmac::Context::with_key(&s_key);
//! for part in &parts {
//!     s_ctx.update(part.as_bytes())?;
//! }
//! let tag = s_ctx.sign()?;
//!
//! // The receiver (somehow!) knows the key value, and uses it to verify the
//! // integrity of the message.
//! let v_key = cmac::Key::new(cmac::AES_256, key_value.as_ref())?;
//! let mut msg = Vec::<u8>::new();
//! for part in &parts {
//!     msg.extend(part.as_bytes());
//! }
//! cmac::verify(&v_key, &msg.as_ref(), tag.as_ref())?;
//!
//! # Ok::<(), ring::error::Unspecified>(())
//! ```
//! [RFC 4493]: https://tools.ietf.org/html/rfc4493
//! [NIST SP 800-38B]: https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38b.pdf

#[cfg(not(feature = "std"))]
use crate::prelude::*;

use crate::error::Unspecified;
use crate::fips::indicator_check;
use crate::ptr::{ConstPointer, LcPtr};
use crate::wolfcrypt_rs::{
    CMAC_CTX_new, CMAC_Final, CMAC_Init, CMAC_Update, EVP_aes_128_cbc, EVP_aes_192_cbc,
    EVP_aes_256_cbc, CMAC_CTX, EVP_CIPHER,
};
use crate::{constant_time, rand};
use core::mem::MaybeUninit;
use core::ptr::null_mut;

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum AlgorithmId {
    Aes128,
    Aes192,
    Aes256,
}

/// A CMAC algorithm.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Algorithm {
    id: AlgorithmId,
    key_len: usize,
    tag_len: usize,
}

impl Algorithm {
    /// The key length for this CMAC algorithm.
    #[inline]
    #[must_use]
    pub fn key_len(&self) -> usize {
        self.key_len
    }

    /// The tag length for this CMAC algorithm.
    #[inline]
    #[must_use]
    pub fn tag_len(&self) -> usize {
        self.tag_len
    }
}

impl AlgorithmId {
    fn evp_cipher(&self) -> ConstPointer<'_, EVP_CIPHER> {
        // SAFETY: EVP_aes_*_cbc() return pointers to static wolfSSL cipher tables.
        unsafe {
            ConstPointer::new_static(match self {
                AlgorithmId::Aes128 => EVP_aes_128_cbc(),
                AlgorithmId::Aes192 => EVP_aes_192_cbc(),
                AlgorithmId::Aes256 => EVP_aes_256_cbc(),
            })
            // PANIC-SAFETY: wolfSSL cipher table is statically linked; null only on build misconfiguration
            .unwrap()
        }
    }
}

/// CMAC using AES-128.
pub const AES_128: Algorithm = Algorithm {
    id: AlgorithmId::Aes128,
    key_len: 16,
    tag_len: 16,
};

/// CMAC using AES-192.
pub const AES_192: Algorithm = Algorithm {
    id: AlgorithmId::Aes192,
    key_len: 24,
    tag_len: 16,
};

/// CMAC using AES-256.
pub const AES_256: Algorithm = Algorithm {
    id: AlgorithmId::Aes256,
    key_len: 32,
    tag_len: 16,
};

/// Maximum CMAC tag length (AES block size).
const MAX_CMAC_TAG_LEN: usize = 16;

/// A CMAC tag.
///
/// For a given tag `t`, use `t.as_ref()` to get the tag value as a byte slice.
#[derive(Clone, Copy, Debug)]
pub struct Tag {
    bytes: [u8; MAX_CMAC_TAG_LEN],
    len: usize,
}

impl AsRef<[u8]> for Tag {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        &self.bytes[..self.len]
    }
}

/// A key to use for CMAC signing.
//
// # FIPS
// Use this type with one of the following algorithms:
// * `AES_128`
// * `AES_256`
pub struct Key {
    algorithm: Algorithm,
    ctx: LcPtr<CMAC_CTX>,
    /// Store the raw key bytes so we can re-init on clone.
    /// wolfSSL doesn't support CMAC_CTX_copy, so we re-create
    /// the context from scratch when cloning.
    key_bytes: Vec<u8>,
}

impl Clone for Key {
    fn clone(&self) -> Self {
        // PANIC-SAFETY: Clone trait is infallible; re-init from stored key bytes cannot fail unless OOM
        Key::new(self.algorithm, &self.key_bytes)
            .expect("CMAC Key clone failed: re-initialization should succeed")
    }
}

unsafe impl Send for Key {}
// All uses of *mut CMAC_CTX require the creation of a Context, which will clone the Key.
unsafe impl Sync for Key {}

#[allow(clippy::missing_fields_in_debug)]
impl core::fmt::Debug for Key {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
        f.debug_struct("Key")
            .field("algorithm", &self.algorithm)
            .finish()
    }
}

impl Key {
    /// Generate a CMAC signing key using the given algorithm with a
    /// random value.
    ///
    //
    // # FIPS
    // Use this type with one of the following algorithms:
    // * `AES_128`
    // * `AES_256`
    //
    /// # Errors
    /// `error::Unspecified` if random generation or key construction fails.
    pub fn generate(algorithm: Algorithm) -> Result<Self, Unspecified> {
        let mut key_bytes = vec![0u8; algorithm.key_len()];
        rand::fill(&mut key_bytes)?;
        Self::new(algorithm, &key_bytes)
    }

    /// Construct a CMAC signing key using the given algorithm and key value.
    ///
    /// `key_value` should be a value generated using a secure random number
    /// generator or derived from a random key by a key derivation function.
    ///
    /// # Errors
    /// `error::Unspecified` if the key length doesn't match the algorithm or if CMAC context
    /// initialization fails.
    pub fn new(algorithm: Algorithm, key_value: &[u8]) -> Result<Self, Unspecified> {
        if key_value.len() != algorithm.key_len() {
            return Err(Unspecified);
        }

        // SAFETY: CMAC_CTX_new returns a heap-allocated context or null (checked by LcPtr::new).
        let mut ctx = LcPtr::new(unsafe { CMAC_CTX_new() })?;

        // SAFETY: ctx is valid (just allocated); key_value pointer/length from a valid Rust slice.
        unsafe {
            let cipher = algorithm.id.evp_cipher();
            if 1 != CMAC_Init(
                ctx.as_mut_ptr(),
                key_value.as_ptr().cast(),
                key_value.len(),
                cipher.as_const_ptr(),
                null_mut(),
            ) {
                return Err(Unspecified);
            }
        }

        Ok(Self {
            algorithm,
            ctx,
            key_bytes: key_value.to_vec(),
        })
    }

    /// The algorithm for the key.
    #[inline]
    #[must_use]
    pub fn algorithm(&self) -> Algorithm {
        self.algorithm
    }
}

/// A context for multi-step (Init-Update-Finish) CMAC signing.
///
/// Use `sign` for single-step CMAC signing.
pub struct Context {
    key: Key,
    /// Accumulated update data for replay on clone. wolfSSL doesn't support
    /// CMAC_CTX_copy, so we replay all updates on the cloned context.
    accumulated_data: Vec<u8>,
}

impl Clone for Context {
    fn clone(&self) -> Self {
        let mut cloned = Self {
            key: self.key.clone(),
            accumulated_data: self.accumulated_data.clone(),
        };
        // Replay all accumulated data on the fresh context
        if !cloned.accumulated_data.is_empty() {
            // SAFETY: ctx is valid (freshly cloned); pointer/length from a valid Rust slice.
            unsafe {
                CMAC_Update(
                    cloned.key.ctx.as_mut_ptr(),
                    cloned.accumulated_data.as_ptr(),
                    cloned.accumulated_data.len(),
                );
            }
        }
        cloned
    }
}

unsafe impl Send for Context {}

impl core::fmt::Debug for Context {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
        f.debug_struct("Context")
            .field("algorithm", &self.key.algorithm)
            .finish()
    }
}

impl Context {
    /// Constructs a new CMAC signing context using the given key.
    #[inline]
    #[must_use]
    pub fn with_key(key: &Key) -> Self {
        Self {
            key: key.clone(),
            accumulated_data: Vec::new(),
        }
    }

    /// Updates the CMAC with all the data in `data`. `update` may be called
    /// zero or more times until `sign` is called.
    ///
    /// # Errors
    /// `error::Unspecified` if the CMAC cannot be updated.
    pub fn update(&mut self, data: &[u8]) -> Result<(), Unspecified> {
        // SAFETY: CMAC_CTX is valid; pointer and length derived from a valid Rust slice.
        unsafe {
            if 1 != CMAC_Update(self.key.ctx.as_mut_ptr(), data.as_ptr(), data.len()) {
                return Err(Unspecified);
            }
        }
        // Track data for potential clone replay
        self.accumulated_data.extend_from_slice(data);
        Ok(())
    }

    /// Finalizes the CMAC calculation and returns the CMAC value. `sign`
    /// consumes the context so it cannot be (mis-)used after `sign` has been
    /// called.
    ///
    /// It is generally not safe to implement CMAC verification by comparing
    /// the return value of `sign` to a tag. Use `verify` for verification
    /// instead.
    ///
    //
    // # FIPS
    // Use this method with one of the following algorithms:
    // * `AES_128`
    // * `AES_256`
    //
    /// # Errors
    /// `error::Unspecified` if the CMAC calculation cannot be finalized.
    ///
    /// # Panics
    /// Panics if the CMAC tag length exceeds the maximum allowed length, indicating memory corruption.
    pub fn sign(mut self) -> Result<Tag, Unspecified> {
        let mut output = [0u8; MAX_CMAC_TAG_LEN];
        let output_len = {
            let result = internal_sign(&mut self, &mut output)?;
            result.len()
        };

        Ok(Tag {
            bytes: output,
            len: output_len,
        })
    }

    /// Finalizes the CMAC calculation and verifies whether the resulting value
    /// equals the provided `tag`.
    ///
    /// `verify` consumes the context so it cannot be (mis-)used after `verify`
    /// has been called.
    ///
    /// The verification is done in constant time to prevent timing attacks.
    ///
    /// # Errors
    /// `error::Unspecified` if the tag does not match or if CMAC calculation fails.
    //
    // # FIPS
    // Use this function with one of the following algorithms:
    // * `AES_128`
    // * `AES_256`
    #[inline]
    pub fn verify(mut self, tag: &[u8]) -> Result<(), Unspecified> {
        let mut output = [0u8; MAX_CMAC_TAG_LEN];
        let output_len = {
            let result = internal_sign(&mut self, &mut output)?;
            result.len()
        };

        constant_time::verify_slices_are_equal(&output[0..output_len], tag)
    }
}

pub(crate) fn internal_sign<'in_out>(
    ctx: &mut Context,
    output: &'in_out mut [u8],
) -> Result<&'in_out mut [u8], Unspecified> {
    let mut out_len = MaybeUninit::<usize>::uninit();

    // SAFETY: CMAC_CTX is valid; output buffer and out_len pointer are valid.
    if 1 != indicator_check!(unsafe {
        CMAC_Final(
            ctx.key.ctx.as_mut_ptr(),
            output.as_mut_ptr(),
            out_len.as_mut_ptr(),
        )
    }) {
        return Err(Unspecified);
    }
    // SAFETY: fully initialized by the successful CMAC_Final call above.
    let actual_len = unsafe { out_len.assume_init() };

    // This indicates a memory corruption.
    debug_assert!(
        actual_len <= MAX_CMAC_TAG_LEN,
        "CMAC tag length {actual_len} exceeds maximum {MAX_CMAC_TAG_LEN}"
    );
    if actual_len != ctx.key.algorithm.tag_len() {
        return Err(Unspecified);
    }

    Ok(&mut output[0..actual_len])
}

/// Calculates the CMAC of `data` using the key `key` in one step.
///
/// Use `Context` to calculate CMACs where the input is in multiple parts.
///
/// It is generally not safe to implement CMAC verification by comparing the
/// return value of `sign` to a tag. Use `verify` for verification instead.
//
// # FIPS
// Use this function with one of the following algorithms:
// * `AES_128`
// * `AES_256`
//
/// # Errors
/// `error::Unspecified` if the CMAC calculation fails.
#[inline]
pub fn sign(key: &Key, data: &[u8]) -> Result<Tag, Unspecified> {
    let mut ctx = Context::with_key(key);
    ctx.update(data)?;
    ctx.sign()
}

/// Calculates the CMAC of `data` using the key `key` in one step, writing the
/// result into the provided `output` buffer.
///
/// Use `Context` to calculate CMACs where the input is in multiple parts.
///
/// The `output` buffer must be at least as large as the algorithm's tag length
/// (obtainable via `key.algorithm().tag_len()`). The returned slice will be a
/// sub-slice of `output` containing exactly the tag bytes.
///
/// It is generally not safe to implement CMAC verification by comparing the
/// return value of `sign_to_buffer` to a tag. Use `verify` for verification instead.
//
// # FIPS
// Use this function with one of the following algorithms:
// * `AES_128`
// * `AES_256`
//
/// # Errors
/// `error::Unspecified` if the output buffer is too small or if the CMAC calculation fails.
#[inline]
pub fn sign_to_buffer<'out>(
    key: &Key,
    data: &[u8],
    output: &'out mut [u8],
) -> Result<&'out mut [u8], Unspecified> {
    if output.len() < key.algorithm().tag_len() {
        return Err(Unspecified);
    }

    let mut ctx = Context::with_key(key);
    ctx.update(data)?;

    internal_sign(&mut ctx, output)
}

/// Calculates the CMAC of `data` using the signing key `key`, and verifies
/// whether the resultant value equals `tag`, in one step.
///
/// The verification is done in constant time to prevent timing attacks.
///
/// # Errors
/// `error::Unspecified` if the tag does not match or if CMAC calculation fails.
//
// # FIPS
// Use this function with one of the following algorithms:
// * `AES_128`
// * `AES_256`
#[inline]
pub fn verify(key: &Key, data: &[u8], tag: &[u8]) -> Result<(), Unspecified> {
    let mut output = [0u8; MAX_CMAC_TAG_LEN];
    let output_len = {
        let result = sign_to_buffer(key, data, &mut output)?;
        result.len()
    };

    constant_time::verify_slices_are_equal(&output[0..output_len], tag)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg(feature = "fips")]
    mod fips;

    #[test]
    fn cmac_basic_test() {
        for &algorithm in &[AES_128, AES_192, AES_256] {
            let key = Key::generate(algorithm).unwrap();
            let data = b"hello, world";

            let tag = sign(&key, data).unwrap();
            assert!(verify(&key, data, tag.as_ref()).is_ok());
            assert!(verify(&key, b"hello, worle", tag.as_ref()).is_err());
        }
    }

    // Make sure that `Key::generate` and `verify` aren't completely wacky.
    #[test]
    pub fn cmac_signing_key_coverage() {
        const HELLO_WORLD_GOOD: &[u8] = b"hello, world";
        const HELLO_WORLD_BAD: &[u8] = b"hello, worle";

        for algorithm in &[AES_128, AES_192, AES_256] {
            let key = Key::generate(*algorithm).unwrap();
            let tag = sign(&key, HELLO_WORLD_GOOD).unwrap();
            println!("{key:?}");
            assert!(verify(&key, HELLO_WORLD_GOOD, tag.as_ref()).is_ok());
            assert!(verify(&key, HELLO_WORLD_BAD, tag.as_ref()).is_err());
        }
    }

    #[test]
    fn cmac_coverage() {
        // Something would have gone horribly wrong for this to not pass, but we test this so our
        // coverage reports will look better.
        assert_ne!(AES_128, AES_256);
        assert_ne!(AES_192, AES_256);

        for &alg in &[AES_128, AES_192, AES_256] {
            // Clone after updating context with message, then check if the final Tag is the same.
            let key_bytes = vec![0u8; alg.key_len()];
            let key = Key::new(alg, &key_bytes).unwrap();
            let mut ctx = Context::with_key(&key);
            ctx.update(b"hello, world").unwrap();
            let ctx_clone = ctx.clone();

            let orig_tag = ctx.sign().unwrap();
            let clone_tag = ctx_clone.sign().unwrap();
            assert_eq!(orig_tag.as_ref(), clone_tag.as_ref());
            assert_eq!(orig_tag.clone().as_ref(), clone_tag.as_ref());
        }
    }

    #[test]
    fn cmac_context_test() {
        let key = Key::generate(AES_192).unwrap();

        let mut ctx = Context::with_key(&key);
        ctx.update(b"hello").unwrap();
        ctx.update(b", ").unwrap();
        ctx.update(b"world").unwrap();
        let tag1 = ctx.sign().unwrap();

        let tag2 = sign(&key, b"hello, world").unwrap();
        assert_eq!(tag1.as_ref(), tag2.as_ref());
    }

    #[test]
    fn cmac_multi_part_test() {
        let parts = ["hello", ", ", "world"];

        for &algorithm in &[AES_128, AES_256] {
            let key = Key::generate(algorithm).unwrap();

            // Multi-part signing
            let mut ctx = Context::with_key(&key);
            for part in &parts {
                ctx.update(part.as_bytes()).unwrap();
            }
            let tag = ctx.sign().unwrap();

            // Verification with concatenated message
            let mut msg = Vec::<u8>::new();
            for part in &parts {
                msg.extend(part.as_bytes());
            }
            assert!(verify(&key, &msg, tag.as_ref()).is_ok());
        }
    }

    #[test]
    fn cmac_key_new_test() {
        // Test Key::new with explicit key values
        let key_128 = [0u8; 16];
        let key_192 = [0u8; 24];
        let key_256 = [0u8; 32];

        let k1 = Key::new(AES_128, &key_128).unwrap();
        let k2 = Key::new(AES_192, &key_192).unwrap();
        let k3 = Key::new(AES_256, &key_256).unwrap();

        let data = b"test message";

        // All should produce valid tags
        let _ = sign(&k1, data).unwrap();
        let _ = sign(&k2, data).unwrap();
        let _ = sign(&k3, data).unwrap();
    }

    #[test]
    fn cmac_key_new_wrong_length_test() {
        let key_256 = [0u8; 32];
        // Wrong key length should return error
        assert!(Key::new(AES_128, &key_256).is_err());
    }

    #[test]
    fn cmac_algorithm_properties() {
        assert_eq!(AES_128.key_len(), 16);
        assert_eq!(AES_128.tag_len(), 16);

        assert_eq!(AES_192.key_len(), 24);
        assert_eq!(AES_192.tag_len(), 16);

        assert_eq!(AES_256.key_len(), 32);
        assert_eq!(AES_256.tag_len(), 16);
    }

    #[test]
    fn cmac_empty_data() {
        let key = Key::generate(AES_128).unwrap();

        // CMAC should work with empty data
        let tag = sign(&key, b"").unwrap();
        assert!(verify(&key, b"", tag.as_ref()).is_ok());

        // Context version
        let ctx = Context::with_key(&key);
        let tag2 = ctx.sign().unwrap();
        assert_eq!(tag.as_ref(), tag2.as_ref());
    }

    #[test]
    fn cmac_sign_to_buffer_test() {
        for &algorithm in &[AES_128, AES_192, AES_256] {
            let key = Key::generate(algorithm).unwrap();
            let data = b"hello, world";

            // Test with exact size buffer
            let mut output = vec![0u8; algorithm.tag_len()];
            let result = sign_to_buffer(&key, data, &mut output).unwrap();
            assert_eq!(result.len(), algorithm.tag_len());

            // Verify the tag matches sign()
            let tag = sign(&key, data).unwrap();
            assert_eq!(result, tag.as_ref());

            // Test with larger buffer
            let mut large_output = vec![0u8; algorithm.tag_len() + 10];
            let result2 = sign_to_buffer(&key, data, &mut large_output).unwrap();
            assert_eq!(result2.len(), algorithm.tag_len());
            assert_eq!(result2, tag.as_ref());
        }
    }

    #[test]
    fn cmac_sign_to_buffer_too_small_test() {
        let key = Key::generate(AES_128).unwrap();
        let data = b"hello";

        // Buffer too small should fail
        let mut small_buffer = vec![0u8; AES_128.tag_len() - 1];
        assert!(sign_to_buffer(&key, data, &mut small_buffer).is_err());

        // Empty buffer should fail
        let mut empty_buffer = vec![];
        assert!(sign_to_buffer(&key, data, &mut empty_buffer).is_err());
    }

    #[test]
    fn cmac_context_verify_test() {
        for &algorithm in &[AES_128, AES_192, AES_256] {
            let key = Key::generate(algorithm).unwrap();
            let data = b"hello, world";

            // Generate a valid tag
            let tag = sign(&key, data).unwrap();

            // Verify with Context::verify
            let mut ctx = Context::with_key(&key);
            ctx.update(data).unwrap();
            assert!(ctx.verify(tag.as_ref()).is_ok());

            // Verify with wrong tag should fail
            let mut ctx2 = Context::with_key(&key);
            ctx2.update(data).unwrap();
            let wrong_tag = vec![0u8; algorithm.tag_len()];
            assert!(ctx2.verify(&wrong_tag).is_err());

            // Verify with different data should fail
            let mut ctx3 = Context::with_key(&key);
            ctx3.update(b"wrong data").unwrap();
            assert!(ctx3.verify(tag.as_ref()).is_err());
        }
    }

    #[test]
    fn cmac_context_verify_multipart_test() {
        let key = Key::generate(AES_256).unwrap();
        let parts = ["hello", ", ", "world"];

        // Create tag from concatenated message
        let mut full_msg = Vec::new();
        for part in &parts {
            full_msg.extend_from_slice(part.as_bytes());
        }
        let tag = sign(&key, &full_msg).unwrap();

        // Verify using multi-part context
        let mut ctx = Context::with_key(&key);
        for part in &parts {
            ctx.update(part.as_bytes()).unwrap();
        }
        assert!(ctx.verify(tag.as_ref()).is_ok());

        // Verify with missing part should fail
        let mut ctx2 = Context::with_key(&key);
        ctx2.update(parts[0].as_bytes()).unwrap();
        ctx2.update(parts[1].as_bytes()).unwrap();
        // Missing parts[2]
        assert!(ctx2.verify(tag.as_ref()).is_err());
    }

    /// RFC 4493 test vectors for AES-128 CMAC.
    /// Key = 2b7e1516 28aed2a6 abf71588 09cf4f3c
    #[test]
    fn cmac_rfc4493_known_answer() {
        let key_bytes: [u8; 16] = [
            0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf,
            0x4f, 0x3c,
        ];
        let key = Key::new(AES_128, &key_bytes).unwrap();

        // Example 1: empty message
        // Expected: bb1d6929 e9593728 7fa37d12 9b756746
        let tag = sign(&key, b"").unwrap();
        assert_eq!(
            tag.as_ref(),
            &[
                0xbb, 0x1d, 0x69, 0x29, 0xe9, 0x59, 0x37, 0x28, 0x7f, 0xa3, 0x7d, 0x12, 0x9b, 0x75,
                0x67, 0x46
            ]
        );

        // Example 2: 16-byte message (one block)
        // M = 6bc1bee2 2e409f96 e93d7e11 7393172a
        // Expected: 070a16b4 6b4d4144 f79bdd9d d04a287c
        let msg2: [u8; 16] = [
            0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93,
            0x17, 0x2a,
        ];
        let tag2 = sign(&key, &msg2).unwrap();
        assert_eq!(
            tag2.as_ref(),
            &[
                0x07, 0x0a, 0x16, 0xb4, 0x6b, 0x4d, 0x41, 0x44, 0xf7, 0x9b, 0xdd, 0x9d, 0xd0, 0x4a,
                0x28, 0x7c
            ]
        );

        // Example 3: 40-byte message (not block-aligned)
        // M = 6bc1bee2 2e409f96 e93d7e11 7393172a
        //     ae2d8a57 1e03ac9c 9eb76fac 45af8e51
        //     30c81c46 a35ce411
        // Expected: dfa66747 de9ae630 30ca3261 1497c827
        let msg3: [u8; 40] = [
            0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93,
            0x17, 0x2a, 0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c, 0x9e, 0xb7, 0x6f, 0xac,
            0x45, 0xaf, 0x8e, 0x51, 0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11,
        ];
        let tag3 = sign(&key, &msg3).unwrap();
        assert_eq!(
            tag3.as_ref(),
            &[
                0xdf, 0xa6, 0x67, 0x47, 0xde, 0x9a, 0xe6, 0x30, 0x30, 0xca, 0x32, 0x61, 0x14, 0x97,
                0xc8, 0x27
            ]
        );

        // Example 4: 64-byte message (4 blocks)
        // M = 6bc1bee2 2e409f96 e93d7e11 7393172a
        //     ae2d8a57 1e03ac9c 9eb76fac 45af8e51
        //     30c81c46 a35ce411 e5fbc119 1a0a52ef
        //     f69f2445 df4f9b17 ad2b417b e66c3710
        // Expected: 51f0bebf 7e3b9d92 fc497417 79363cfe
        let msg4: [u8; 64] = [
            0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93,
            0x17, 0x2a, 0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c, 0x9e, 0xb7, 0x6f, 0xac,
            0x45, 0xaf, 0x8e, 0x51, 0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11, 0xe5, 0xfb,
            0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef, 0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17,
            0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10,
        ];
        let tag4 = sign(&key, &msg4).unwrap();
        assert_eq!(
            tag4.as_ref(),
            &[
                0x51, 0xf0, 0xbe, 0xbf, 0x7e, 0x3b, 0x9d, 0x92, 0xfc, 0x49, 0x74, 0x17, 0x79, 0x36,
                0x3c, 0xfe
            ]
        );
    }

    /// Negative test: verify must reject a corrupted tag.
    #[test]
    fn cmac_verify_rejects_corrupted_tag() {
        let key_bytes: [u8; 16] = [
            0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf,
            0x4f, 0x3c,
        ];
        let key = Key::new(AES_128, &key_bytes).unwrap();
        let msg = b"hello, world";
        let tag = sign(&key, msg).unwrap();

        // Flip one bit in the tag
        let mut bad_tag = tag.as_ref().to_vec();
        bad_tag[0] ^= 0x01;
        assert!(verify(&key, msg, &bad_tag).is_err());

        // Truncated tag should also fail
        assert!(verify(&key, msg, &tag.as_ref()[..15]).is_err());

        // Empty tag should fail
        assert!(verify(&key, msg, &[]).is_err());
    }
}