seal-crypto-wrapper 0.1.0

A high-level, misuse-resistant cryptographic wrapper library for Rust, binding algorithms to keys to ensure type safety.
Documentation
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
//! Aead encryption algorithm wrappers with AEAD support.
//!
//! 支持 AEAD 的对称加密算法包装器。
//!
//! ## Overview | 概述
//!
//! This module provides concrete implementations of aead encryption algorithms
//! that support Authenticated Encryption with Associated Data (AEAD). Each wrapper
//! implements the `AeadAlgorithmTrait` and provides type-safe access to the
//! underlying cryptographic operations.
//!
//! 此模块提供支持带关联数据认证加密 (AEAD) 的对称加密算法的具体实现。
//! 每个包装器都实现 `AeadAlgorithmTrait` 并提供对底层密码操作的类型安全访问。
//!
//! ## Supported Algorithms | 支持的算法
//!
//! - **AES-128-GCM**: Fast, hardware-accelerated, 128-bit security
//! - **AES-256-GCM**: Fast, hardware-accelerated, 256-bit security
//! - **ChaCha20-Poly1305**: Software-optimized, 256-bit security
//! - **XChaCha20-Poly1305**: Extended nonce variant, 256-bit security
//!
//! ## Key Features | 关键特性
//!
//! ### Type Safety | 类型安全
//! - Algorithm-key binding verification
//! - Runtime compatibility checking
//! - Compile-time algorithm selection
//!
//! ### Performance | 性能
//! - Zero-allocation buffer operations
//! - Hardware acceleration when available
//! - Optimized software implementations
//!
//! ### Security | 安全性
//! - Authenticated encryption (confidentiality + integrity)
//! - Associated data authentication
//! - Constant-time operations
//! - Secure memory management
//!
//! ## Usage Examples | 使用示例
//!
//! ### Basic Encryption | 基本加密
//!
//! ```rust
//! use seal_crypto_wrapper::algorithms::aead::AeadAlgorithm;
//!
//! let algorithm = AeadAlgorithm::build().aes256_gcm();
//! let cipher = algorithm.into_wrapper();
//! let key = cipher.generate_typed_key()?;
//!
//! let plaintext = b"Hello, World!";
//! let nonce = vec![0u8; cipher.nonce_size()]; // Use random nonce in production
//! let ciphertext = cipher.encrypt(plaintext, &key, &nonce, None)?;
//!
//! let decrypted = cipher.decrypt(&ciphertext, &key, &nonce, None)?;
//! assert_eq!(plaintext, &decrypted[..]);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! ### With Associated Data | 使用关联数据
//!
//! ```rust
//! use seal_crypto_wrapper::algorithms::aead::AeadAlgorithm;
//!
//! let cipher = AeadAlgorithm::build().chacha20_poly1305().into_wrapper();
//! let key = cipher.generate_typed_key()?;
//!
//! let plaintext = b"Secret message";
//! let aad = b"public header";
//! let nonce = vec![0u8; cipher.nonce_size()];
//!
//! let ciphertext = cipher.encrypt(plaintext, &key, &nonce, Some(aad))?;
//! let decrypted = cipher.decrypt(&ciphertext, &key, &nonce, Some(aad))?;
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use crate::algorithms::aead::{AeadAlgorithm, AesKeySize};
use crate::error::{Error, FormatError, Result};
use crate::keys::aead::{AeadKey as UntypedAeadKey, TypedAeadKey};
use crate::traits::AeadAlgorithmTrait;
use rand::TryRngCore;
use rand::rngs::OsRng;
use seal_crypto::prelude::{AeadCipher, AeadDecryptor, AeadEncryptor, Key};
use seal_crypto::schemes::aead::aes_gcm::{Aes128Gcm, Aes256Gcm};
use seal_crypto::schemes::aead::chacha20_poly1305::{ChaCha20Poly1305, XChaCha20Poly1305};
use std::ops::Deref;

/// Macro for implementing aead algorithm wrappers.
///
/// 用于实现对称算法包装器的宏。
///
/// This macro generates a complete wrapper implementation for a aead algorithm,
/// including all required trait methods, key validation, and error handling.
///
/// 此宏为对称算法生成完整的包装器实现,
/// 包括所有必需的 trait 方法、密钥验证和错误处理。
///
/// ## Parameters | 参数
///
/// - `$wrapper`: The name of the wrapper struct to generate
/// - `$algo`: The underlying algorithm type from seal-crypto
/// - `$algo_enum`: The corresponding algorithm enum variant
///
/// - `$wrapper`: 要生成的包装器结构体名称
/// - `$algo`: 来自 seal-crypto 的底层算法类型
/// - `$algo_enum`: 对应的算法枚举变体
macro_rules! impl_aead_algorithm {
    ($wrapper:ident, $algo:ty, $algo_enum:expr) => {
        /// Wrapper implementation for a specific aead algorithm.
        ///
        /// 特定对称算法的包装器实现。
        ///
        /// This struct provides a type-safe interface to the underlying cryptographic
        /// algorithm, ensuring that keys are validated and operations are performed
        /// with the correct algorithm parameters.
        ///
        /// 此结构体为底层密码算法提供类型安全接口,
        /// 确保密钥得到验证并使用正确的算法参数执行操作。
        #[derive(Clone, Debug, Default)]
        pub struct $wrapper;

        impl $wrapper {
            pub fn new() -> Self {
                Self
            }
        }

        impl From<$wrapper> for Box<dyn AeadAlgorithmTrait> {
            fn from(wrapper: $wrapper) -> Self {
                Box::new(wrapper)
            }
        }

        impl AeadAlgorithmTrait for $wrapper {
            fn encrypt(
                &self,
                plaintext: &[u8],
                key: &TypedAeadKey,
                nonce: &[u8],
                aad: Option<&[u8]>,
            ) -> Result<Vec<u8>> {
                if key.algorithm() != $algo_enum {
                    return Err(Error::FormatError(FormatError::InvalidKeyType));
                }
                type KT = $algo;
                let key =
                    <KT as seal_crypto::prelude::SymmetricKeySet>::Key::from_bytes(key.as_bytes())?;
                KT::encrypt(&key, nonce, plaintext, aad).map_err(Error::from)
            }

            fn encrypt_to_buffer(
                &self,
                plaintext: &[u8],
                output: &mut [u8],
                key: &TypedAeadKey,
                nonce: &[u8],
                aad: Option<&[u8]>,
            ) -> Result<usize> {
                if key.algorithm() != $algo_enum {
                    return Err(Error::FormatError(FormatError::InvalidKeyType));
                }
                type KT = $algo;
                let key =
                    <KT as seal_crypto::prelude::SymmetricKeySet>::Key::from_bytes(key.as_bytes())?;
                KT::encrypt_to_buffer(&key, nonce, plaintext, output, aad).map_err(Error::from)
            }

            fn decrypt(
                &self,
                ciphertext: &[u8],
                key: &TypedAeadKey,
                nonce: &[u8],
                aad: Option<&[u8]>,
            ) -> Result<Vec<u8>> {
                if key.algorithm() != $algo_enum {
                    return Err(Error::FormatError(FormatError::InvalidKeyType));
                }
                type KT = $algo;
                let key =
                    <KT as seal_crypto::prelude::SymmetricKeySet>::Key::from_bytes(key.as_bytes())?;
                KT::decrypt(&key, nonce, ciphertext, aad).map_err(Error::from)
            }

            fn decrypt_to_buffer(
                &self,
                ciphertext: &[u8],
                output: &mut [u8],
                key: &TypedAeadKey,
                nonce: &[u8],
                aad: Option<&[u8]>,
            ) -> Result<usize> {
                if key.algorithm() != $algo_enum {
                    return Err(Error::FormatError(FormatError::InvalidKeyType));
                }
                type KT = $algo;
                let key =
                    <KT as seal_crypto::prelude::SymmetricKeySet>::Key::from_bytes(key.as_bytes())?;
                KT::decrypt_to_buffer(&key, nonce, ciphertext, output, aad).map_err(Error::from)
            }

            fn clone_box(&self) -> Box<dyn AeadAlgorithmTrait> {
                Box::new(self.clone())
            }

            fn algorithm(&self) -> AeadAlgorithm {
                $algo_enum
            }

            fn key_size(&self) -> usize {
                <$algo>::KEY_SIZE
            }

            fn nonce_size(&self) -> usize {
                <$algo>::NONCE_SIZE
            }

            fn tag_size(&self) -> usize {
                <$algo>::TAG_SIZE
            }

            fn generate_typed_key(&self) -> Result<TypedAeadKey> {
                TypedAeadKey::generate($algo_enum)
            }

            fn generate_untyped_key(&self) -> Result<UntypedAeadKey> {
                self.generate_typed_key().map(|k| k.untyped())
            }

            fn into_boxed(self) -> Box<dyn AeadAlgorithmTrait> {
                Box::new(self)
            }
        }
    };
}

/// Universal wrapper for aead encryption algorithms.
///
/// 对称加密算法的通用包装器。
///
/// ## Purpose | 目的
///
/// This wrapper provides a unified interface for all aead encryption algorithms,
/// allowing runtime algorithm selection while maintaining type safety. It acts as
/// a bridge between algorithm enums and concrete implementations.
///
/// 此包装器为所有对称加密算法提供统一接口,
/// 允许运行时算法选择同时保持类型安全。它充当算法枚举和具体实现之间的桥梁。
///
/// ## Features | 特性
///
/// - **Runtime Polymorphism**: Switch between algorithms at runtime
/// - **Type Safety**: Maintains algorithm-key binding verification
/// - **Unified Interface**: Same API for all aead algorithms
/// - **Performance**: Zero-cost abstractions where possible
///
/// - **运行时多态性**: 在运行时切换算法
/// - **类型安全**: 保持算法-密钥绑定验证
/// - **统一接口**: 所有对称算法的相同 API
/// - **性能**: 尽可能的零成本抽象
///
/// ## Examples | 示例
///
/// ```rust
/// use seal_crypto_wrapper::algorithms::aead::AeadAlgorithm;
/// use seal_crypto_wrapper::wrappers::aead::AeadAlgorithmWrapper;
///
/// // Create from algorithm enum
/// let algorithm = AeadAlgorithm::build().aes256_gcm();
/// let wrapper = AeadAlgorithmWrapper::from_enum(algorithm);
///
/// // Use unified interface
/// let key = wrapper.generate_typed_key()?;
/// let plaintext = b"Hello, World!";
/// let nonce = vec![0u8; wrapper.nonce_size()];
/// let ciphertext = wrapper.encrypt(plaintext, &key, &nonce, None)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Clone, Debug)]
pub struct AeadAlgorithmWrapper {
    pub(crate) algorithm: Box<dyn AeadAlgorithmTrait>,
}

impl Deref for AeadAlgorithmWrapper {
    type Target = Box<dyn AeadAlgorithmTrait>;

    fn deref(&self) -> &Self::Target {
        &self.algorithm
    }
}

impl Into<Box<dyn AeadAlgorithmTrait>> for AeadAlgorithmWrapper {
    fn into(self) -> Box<dyn AeadAlgorithmTrait> {
        self.algorithm
    }
}

impl AeadAlgorithmWrapper {
    /// Creates a new wrapper from a boxed trait object.
    ///
    /// 从 boxed trait 对象创建新的包装器。
    ///
    /// This constructor allows you to wrap any implementation of
    /// `AeadAlgorithmTrait` in the universal wrapper interface.
    ///
    /// 此构造函数允许您将 `AeadAlgorithmTrait` 的任何实现
    /// 包装在通用包装器接口中。
    ///
    /// ## Arguments | 参数
    ///
    /// * `algorithm` - A boxed trait object implementing the aead algorithm
    ///
    /// * `algorithm` - 实现对称算法的 boxed trait 对象
    pub fn new(algorithm: Box<dyn AeadAlgorithmTrait>) -> Self {
        Self { algorithm }
    }

    /// Creates a wrapper from a aead algorithm enum.
    ///
    /// 从对称算法枚举创建包装器。
    ///
    /// This is the most common way to create a wrapper, as it automatically
    /// selects the appropriate concrete implementation based on the algorithm.
    ///
    /// 这是创建包装器的最常见方式,因为它根据算法自动选择适当的具体实现。
    ///
    /// ## Arguments | 参数
    ///
    /// * `algorithm` - The aead algorithm enum variant
    ///
    /// * `algorithm` - 对称算法枚举变体
    ///
    /// ## Examples | 示例
    ///
    /// ```rust
    /// use seal_crypto_wrapper::algorithms::aead::AeadAlgorithm;
    /// use seal_crypto_wrapper::wrappers::aead::AeadAlgorithmWrapper;
    ///
    /// let aes = AeadAlgorithmWrapper::from_enum(
    ///     AeadAlgorithm::build().aes256_gcm()
    /// );
    ///
    /// let chacha = AeadAlgorithmWrapper::from_enum(
    ///     AeadAlgorithm::build().chacha20_poly1305()
    /// );
    /// ```
    pub fn from_enum(algorithm: AeadAlgorithm) -> Self {
        let algorithm: Box<dyn AeadAlgorithmTrait> = match algorithm {
            AeadAlgorithm::AesGcm(AesKeySize::K128) => Box::new(Aes128GcmWrapper::new()),
            AeadAlgorithm::AesGcm(AesKeySize::K256) => Box::new(Aes256GcmWrapper::new()),
            AeadAlgorithm::ChaCha20Poly1305 => Box::new(ChaCha20Poly1305Wrapper::new()),
            AeadAlgorithm::XChaCha20Poly1305 => Box::new(XChaCha20Poly1305Wrapper::new()),
        };
        Self::new(algorithm)
    }

    /// Generates a new algorithm-bound typed key.
    ///
    /// 生成新的算法绑定类型化密钥。
    ///
    /// The generated key is automatically bound to the algorithm used by this wrapper,
    /// ensuring type safety for all subsequent operations.
    ///
    /// 生成的密钥自动绑定到此包装器使用的算法,
    /// 确保所有后续操作的类型安全。
    ///
    /// ## Returns | 返回值
    ///
    /// A new `TypedAeadKey` that can only be used with this algorithm.
    ///
    /// 只能与此算法一起使用的新 `TypedAeadKey`。
    ///
    /// ## Examples | 示例
    ///
    /// ```rust
    /// use seal_crypto_wrapper::algorithms::aead::AeadAlgorithm;
    ///
    /// let cipher = AeadAlgorithm::build().aes256_gcm().into_wrapper();
    /// let key = cipher.generate_typed_key()?;
    ///
    /// // Key is bound to AES-256-GCM
    /// assert_eq!(key.algorithm(), AeadAlgorithm::build().aes256_gcm());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn generate_typed_key(&self) -> Result<TypedAeadKey> {
        self.algorithm.generate_typed_key()
    }

    /// Generates a new untyped key.
    ///
    /// 生成新的非类型化密钥。
    ///
    /// This method generates key material without algorithm binding,
    /// which can be useful for key derivation or storage scenarios.
    ///
    /// 此方法生成没有算法绑定的密钥材料,
    /// 这对密钥派生或存储场景很有用。
    ///
    /// ## Security Note | 安全注意
    ///
    /// Untyped keys lose algorithm binding information. Use `generate_typed_key()`
    /// when possible to maintain type safety.
    ///
    /// 非类型化密钥失去算法绑定信息。尽可能使用 `generate_typed_key()`
    /// 以保持类型安全。
    pub fn generate_untyped_key(&self) -> Result<UntypedAeadKey> {
        self.algorithm.generate_untyped_key()
    }

    /// Generates a new nonce.
    ///
    /// 生成新的 nonce。
    ///
    /// This method generates a random nonce for the aead algorithm.
    ///
    /// 此方法生成对称算法的随机 nonce。
    ///
    /// ## Returns | 返回值
    ///
    /// A new nonce for the aead algorithm.
    ///
    /// 对称算法的新的 nonce。
    ///
    pub fn generate_nonce(&self) -> Result<Vec<u8>> {
        let mut nonce = vec![0u8; self.nonce_size()];
        OsRng.try_fill_bytes(&mut nonce)?;
        Ok(nonce)
    }
}

impl AeadAlgorithmTrait for AeadAlgorithmWrapper {
    fn encrypt(
        &self,
        plaintext: &[u8],
        key: &TypedAeadKey,
        nonce: &[u8],
        aad: Option<&[u8]>,
    ) -> Result<Vec<u8>> {
        self.algorithm.encrypt(plaintext, key, nonce, aad)
    }

    fn encrypt_to_buffer(
        &self,
        plaintext: &[u8],
        output: &mut [u8],
        key: &TypedAeadKey,
        nonce: &[u8],
        aad: Option<&[u8]>,
    ) -> Result<usize> {
        self.algorithm
            .encrypt_to_buffer(plaintext, output, key, nonce, aad)
    }

    fn decrypt(
        &self,
        ciphertext: &[u8],
        key: &TypedAeadKey,
        nonce: &[u8],
        aad: Option<&[u8]>,
    ) -> Result<Vec<u8>> {
        self.algorithm.decrypt(ciphertext, key, nonce, aad)
    }

    fn decrypt_to_buffer(
        &self,
        ciphertext: &[u8],
        output: &mut [u8],
        key: &TypedAeadKey,
        nonce: &[u8],
        aad: Option<&[u8]>,
    ) -> Result<usize> {
        self.algorithm
            .decrypt_to_buffer(ciphertext, output, key, nonce, aad)
    }

    fn generate_typed_key(&self) -> Result<TypedAeadKey> {
        self.algorithm.generate_typed_key()
    }

    fn generate_untyped_key(&self) -> Result<UntypedAeadKey> {
        self.algorithm.generate_untyped_key()
    }

    fn algorithm(&self) -> AeadAlgorithm {
        self.algorithm.algorithm()
    }

    fn key_size(&self) -> usize {
        self.algorithm.key_size()
    }

    fn nonce_size(&self) -> usize {
        self.algorithm.nonce_size()
    }

    fn tag_size(&self) -> usize {
        self.algorithm.tag_size()
    }

    fn into_boxed(self) -> Box<dyn AeadAlgorithmTrait> {
        self.algorithm
    }

    fn clone_box(&self) -> Box<dyn AeadAlgorithmTrait> {
        Box::new(self.clone())
    }
}

impl From<AeadAlgorithm> for AeadAlgorithmWrapper {
    fn from(algorithm: AeadAlgorithm) -> Self {
        Self::from_enum(algorithm)
    }
}

impl From<Box<dyn AeadAlgorithmTrait>> for AeadAlgorithmWrapper {
    fn from(algorithm: Box<dyn AeadAlgorithmTrait>) -> Self {
        Self::new(algorithm)
    }
}

impl_aead_algorithm!(
    Aes128GcmWrapper,
    Aes128Gcm,
    AeadAlgorithm::AesGcm(AesKeySize::K128)
);

impl_aead_algorithm!(
    Aes256GcmWrapper,
    Aes256Gcm,
    AeadAlgorithm::AesGcm(AesKeySize::K256)
);

impl_aead_algorithm!(
    ChaCha20Poly1305Wrapper,
    ChaCha20Poly1305,
    AeadAlgorithm::ChaCha20Poly1305
);

impl_aead_algorithm!(
    XChaCha20Poly1305Wrapper,
    XChaCha20Poly1305,
    AeadAlgorithm::XChaCha20Poly1305
);

#[cfg(test)]
mod tests {
    #[cfg(feature = "kdf")]
    use crate::algorithms::kdf::{key::KdfKeyAlgorithm, passwd::KdfPasswordAlgorithm};
    #[cfg(feature = "xof")]
    use crate::algorithms::xof::XofAlgorithm;
    use crate::keys::aead::{AeadKey, TypedAeadKey};
    use crate::prelude::AeadAlgorithm;
    use seal_crypto::secrecy::SecretBox;

    #[test]
    fn test_symmetric_key_generate() {
        use crate::keys::aead::AeadKey;
        use seal_crypto::{prelude::AeadCipher, schemes::aead::aes_gcm::Aes256Gcm};

        let key_len = <Aes256Gcm as AeadCipher>::KEY_SIZE;
        let key1 = AeadKey::generate(key_len).unwrap();
        let key2 = AeadKey::generate(key_len).unwrap();

        assert_eq!(key1.as_bytes().len(), key_len);
        assert_eq!(key2.as_bytes().len(), key_len);
        assert_ne!(
            key1.as_bytes(),
            key2.as_bytes(),
            "Generated keys should be unique"
        );
    }

    #[test]
    fn test_symmetric_key_from_bytes() {
        let key_bytes = vec![0u8; 32];
        let key = AeadKey::new(key_bytes.clone());

        assert_eq!(key.as_bytes(), key_bytes.as_slice());
    }

    #[test]
    #[cfg(feature = "kdf")]
    fn test_typed_symmetric_key_derive_from_kdf() {
        // 使用HKDF-SHA256进行密钥派生
        let master_key_bytes = vec![0u8; 32];

        // 使用不同的上下文信息派生出不同的子密钥
        let salt = b"salt_value";
        let info1 = b"encryption_key";
        let info2 = b"signing_key";
        let kdf_algorithm = KdfKeyAlgorithm::build().hkdf_sha256();
        let symmetric_algorithm = AeadAlgorithm::build().aes256_gcm();

        let derived_key1 = TypedAeadKey::derive_from_kdf(
            &master_key_bytes,
            kdf_algorithm.clone(),
            Some(salt),
            Some(info1),
            symmetric_algorithm,
        )
        .unwrap();

        let derived_key2 = TypedAeadKey::derive_from_kdf(
            &master_key_bytes,
            kdf_algorithm.clone(),
            Some(salt),
            Some(info2),
            symmetric_algorithm,
        )
        .unwrap();

        // 相同的主密钥和参数应该产生相同的派生密钥
        let derived_key1_again = TypedAeadKey::derive_from_kdf(
            &master_key_bytes,
            kdf_algorithm.clone(),
            Some(salt),
            Some(info1),
            symmetric_algorithm,
        )
        .unwrap();

        // 不同的上下文信息应该产生不同的派生密钥
        assert_ne!(derived_key1.as_bytes(), derived_key2.as_bytes());

        // 相同的参数应该产生相同的派生密钥
        assert_eq!(derived_key1.as_bytes(), derived_key1_again.as_bytes());

        assert_eq!(derived_key1.algorithm(), symmetric_algorithm);
    }

    #[test]
    #[cfg(feature = "kdf")]
    fn test_typed_symmetric_key_derive_from_password() {
        // 使用PBKDF2-SHA256从密码派生密钥
        let password = SecretBox::new(Box::from(b"my_secure_password".as_slice()));
        let salt = b"random_salt_value";
        let symmetric_algorithm = AeadAlgorithm::build().aes256_gcm();

        // 设置较少的迭代次数以加速测试(实际应用中应使用更多迭代)
        let deriver = KdfPasswordAlgorithm::build()
            .pbkdf2_sha256_with_params(1000)
            .into_wrapper();

        let derived_key1 = TypedAeadKey::derive_from_password(
            &password,
            deriver.clone(),
            salt,
            symmetric_algorithm,
        )
        .unwrap();

        // 相同的密码、盐和迭代次数应该产生相同的密钥
        let derived_key2 = TypedAeadKey::derive_from_password(
            &password,
            deriver.clone(),
            salt,
            symmetric_algorithm,
        )
        .unwrap();

        assert_eq!(derived_key1.as_bytes(), derived_key2.as_bytes());

        // 不同的密码应该产生不同的密钥
        let different_password = SecretBox::new(Box::from(b"different_password".as_slice()));
        let derived_key3 = TypedAeadKey::derive_from_password(
            &different_password,
            deriver.clone(),
            salt,
            symmetric_algorithm,
        )
        .unwrap();

        assert_ne!(derived_key1.as_bytes(), derived_key3.as_bytes());

        // 不同的盐应该产生不同的密钥
        let different_salt = b"different_salt_value";
        let derived_key4 = TypedAeadKey::derive_from_password(
            &password,
            deriver.clone(),
            different_salt,
            symmetric_algorithm,
        )
        .unwrap();

        assert_ne!(derived_key1.as_bytes(), derived_key4.as_bytes());

        assert_eq!(derived_key1.algorithm(), symmetric_algorithm);
    }

    #[test]
    #[cfg(feature = "xof")]
    fn test_typed_symmetric_key_derive_from_xof() {
        use crate::traits::XofAlgorithmTrait;

        let seed = [0u8; 32];
        let symmetric_algo_1 = AeadAlgorithm::build().aes128_gcm();
        let symmetric_algo_2 = AeadAlgorithm::build().aes256_gcm();

        let mut reader = XofAlgorithm::build()
            .shake128()
            .into_wrapper()
            .reader(&seed, None, None)
            .unwrap();

        let key1 = TypedAeadKey::derive_from_xof(&mut reader, symmetric_algo_1).unwrap();
        let key2 = TypedAeadKey::derive_from_xof(&mut reader, symmetric_algo_2).unwrap();

        // Keys derived from the same reader should be different
        assert_ne!(key1.as_bytes(), key2.as_bytes());

        // Check key lengths and algorithm binding
        assert_eq!(key1.as_bytes().len(), 16);
        assert_eq!(key1.algorithm(), symmetric_algo_1);

        assert_eq!(key2.as_bytes().len(), 32);
        assert_eq!(key2.algorithm(), symmetric_algo_2);
    }

    #[test]
    #[cfg(feature = "kdf")]
    fn test_kdf_derivation_output_length() {
        let master_key_bytes = vec![0u8; 32];
        let kdf_algorithm = KdfKeyAlgorithm::build().hkdf_sha256();
        let salt = b"salt";
        let info = b"info";

        let sym_alg_128 = AeadAlgorithm::build().aes128_gcm();
        let sym_alg_256 = AeadAlgorithm::build().aes256_gcm();

        // 测试不同长度的输出
        let key_128 = TypedAeadKey::derive_from_kdf(
            &master_key_bytes,
            kdf_algorithm.clone(),
            Some(salt),
            Some(info),
            sym_alg_128,
        )
        .unwrap();
        let key_256 = TypedAeadKey::derive_from_kdf(
            &master_key_bytes,
            kdf_algorithm.clone(),
            Some(salt),
            Some(info),
            sym_alg_256,
        )
        .unwrap();

        assert_eq!(key_128.as_bytes().len(), 16);
        assert_eq!(key_128.algorithm(), sym_alg_128);
        assert_eq!(key_256.as_bytes().len(), 32);
        assert_eq!(key_256.algorithm(), sym_alg_256);
    }
}