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
//! Core traits for type-safe cryptographic algorithm specification.
//!
//! 用于类型安全密码算法规范的核心 trait。
//!
//! ## Overview | 概述
//!
//! This module defines the fundamental traits that enable type-safe cryptographic operations
//! in the seal-crypto-wrapper library. These traits provide object-safe interfaces for
//! different cryptographic primitives while maintaining algorithm-specific type information.
//!
//! 此模块定义了在 seal-crypto-wrapper 库中启用类型安全密码操作的基本 trait。
//! 这些 trait 为不同的密码原语提供对象安全接口,同时保持算法特定的类型信息。
//!
//! ## Design Principles | 设计原则
//!
//! ### Object Safety | 对象安全性
//!
//! All traits in this module are designed to be object-safe, allowing them to be used
//! as trait objects (`Box<dyn Trait>`). This enables runtime polymorphism while
//! maintaining compile-time type safety.
//!
//! 此模块中的所有 trait 都设计为对象安全的,允许它们用作 trait 对象 (`Box<dyn Trait>`)。
//! 这在保持编译时类型安全的同时启用了运行时多态性。
//!
//! ### Algorithm Binding | 算法绑定
//!
//! Each trait includes an `algorithm()` method that returns the specific algorithm
//! enum variant. This allows runtime verification that keys and operations match
//! the expected algorithm.
//!
//! 每个 trait 都包含一个 `algorithm()` 方法,返回特定的算法枚举变体。
//! 这允许运行时验证密钥和操作是否匹配预期的算法。
//!
//! ### Memory Safety | 内存安全
//!
//! Sensitive data is handled using `Zeroizing<Vec<u8>>` and `SecretBox<[u8]>`
//! to ensure proper cleanup and prevent accidental exposure.
//!
//! 敏感数据使用 `Zeroizing<Vec<u8>>` 和 `SecretBox<[u8]>` 处理,
//! 以确保正确清理并防止意外暴露。
//!
//! ## Trait Categories | Trait 分类
//!
//! - **Aead Cryptography**: `AeadAlgorithmTrait` for AEAD ciphers
//! - **Asymmetric KEM**: `KemAlgorithmTrait` for key encapsulation mechanisms
//! - **Digital Signatures**: `SignatureAlgorithmTrait` for signing and verification
//! - **Key Agreement**: `KeyAgreementAlgorithmTrait` for shared secret derivation
//! - **Key Derivation**: `KdfKeyAlgorithmTrait`, `KdfPasswordAlgorithmTrait` for key derivation
//! - **Extendable Output**: `XofAlgorithmTrait` for variable-length output functions
//!
//! - **对称密码学**: `AeadAlgorithmTrait` 用于 AEAD 密码
//! - **非对称 KEM**: `KemAlgorithmTrait` 用于密钥封装机制
//! - **数字签名**: `SignatureAlgorithmTrait` 用于签名和验证
//! - **密钥协商**: `KeyAgreementAlgorithmTrait` 用于共享密钥派生
//! - **密钥派生**: `KdfKeyAlgorithmTrait`, `KdfPasswordAlgorithmTrait` 用于密钥派生
//! - **可扩展输出**: `XofAlgorithmTrait` 用于可变长度输出函数
//!
//! ## Macro Utilities | 宏工具
//!
//! The `impl_trait_for_box!` macro automatically implements traits for `Box<dyn Trait>`
//! types, enabling seamless use of trait objects with the same interface as concrete types.
//!
//! `impl_trait_for_box!` 宏自动为 `Box<dyn Trait>` 类型实现 trait,
//! 使 trait 对象能够与具体类型使用相同的接口。

#[cfg(feature = "asymmetric-key-agreement")]
use crate::algorithms::asymmetric::key_agreement::KeyAgreementAlgorithm;
use crate::algorithms::hash::HashAlgorithm;
#[cfg(feature = "asymmetric-key-agreement")]
use crate::keys::asymmetric::key_agreement::{
    TypedKeyAgreementKeyPair, TypedKeyAgreementPrivateKey, TypedKeyAgreementPublicKey,
};
#[cfg(feature = "asymmetric-signature")]
use crate::keys::asymmetric::signature::{
    TypedSignatureKeyPair, TypedSignaturePrivateKey, TypedSignaturePublicKey,
};
#[cfg(feature = "asymmetric-signature")]
use crate::{
    algorithms::asymmetric::signature::SignatureAlgorithm,
    wrappers::asymmetric::signature::SignatureWrapper,
};
#[cfg(feature = "aead")]
use {
    crate::algorithms::aead::AeadAlgorithm,
    crate::keys::aead::{AeadKey as UntypedAeadKey, TypedAeadKey},
};
#[cfg(feature = "asymmetric-kem")]
use {
    crate::algorithms::asymmetric::kem::KemAlgorithm,
    crate::keys::asymmetric::kem::{
        EncapsulatedKey, SharedSecret, TypedKemKeyPair, TypedKemPrivateKey, TypedKemPublicKey,
    },
};
#[cfg(feature = "kdf")]
use {
    crate::algorithms::kdf::key::KdfKeyAlgorithm,
    crate::algorithms::kdf::passwd::KdfPasswordAlgorithm,
    seal_crypto::secrecy::SecretBox,
};
#[cfg(feature = "xof")]
use {crate::algorithms::xof::XofAlgorithm, crate::wrappers::xof::XofReaderWrapper};
#[cfg(any(
    feature = "kdf",
    feature = "asymmetric-key-agreement"
))]
use seal_crypto::zeroize::Zeroizing;
use crate::error::Result;

/// Macro for automatically implementing traits for `Box<dyn Trait>` types.
///
/// 用于自动为 `Box<dyn Trait>` 类型实现 trait 的宏。
///
/// ## Purpose | 目的
///
/// This macro generates implementations that allow `Box<dyn Trait>` to be used
/// seamlessly as if it were a concrete type implementing the trait. It handles
/// method delegation and provides automatic `Clone` implementation.
///
/// 此宏生成实现,允许 `Box<dyn Trait>` 像具体类型一样无缝使用。
/// 它处理方法委托并提供自动的 `Clone` 实现。
///
/// ## Syntax | 语法
///
/// ```ignore
/// impl_trait_for_box!(TraitName {
///     ref fn method_name(&self, arg: Type) -> ReturnType;
///     self fn consuming_method(self, arg: Type) -> ReturnType;
/// }, clone_method_name);
/// ```
///
/// ## Method Types | 方法类型
///
/// - `ref fn`: Methods that take `&self` - delegated to the inner trait object
/// - `self fn`: Methods that consume `self` - may have custom implementations
///
/// - `ref fn`: 接受 `&self` 的方法 - 委托给内部 trait 对象
/// - `self fn`: 消费 `self` 的方法 - 可能有自定义实现
///
/// ## Examples | 示例
///
/// ```ignore
/// impl_trait_for_box!(AeadAlgorithmTrait {
///     ref fn encrypt(&self, key: &Key, data: &[u8]) -> Result<Vec<u8>>;
///     ref fn decrypt(&self, key: &Key, data: &[u8]) -> Result<Vec<u8>>;
/// }, clone_box_symmetric);
/// ```
#[allow(unused_macros)]
macro_rules! impl_trait_for_box {
    // Internal recursive rules for TT muncher
    (
        @impl,
        $trait:ident,
        $clone_box_name:ident,
        { }, // no more methods
        { $($impls:tt)* } // accumulated impls
    ) => {
        impl Clone for Box<dyn $trait> {
            fn clone(&self) -> Self {
                self.$clone_box_name()
            }
        }

        impl $trait for Box<dyn $trait> {
            $($impls)*
        }
    };

    // Munch a `ref fn` with generics
    (
        @impl,
        $trait:ident,
        $clone_box_name:ident,
        {
            ref fn $method:ident< $($lt:lifetime),+ >(&self, $($arg:ident: $ty:ty),*) -> $ret:ty;
            $($rest:tt)*
        },
        { $($impls:tt)* }
    ) => {
        impl_trait_for_box! {
            @impl,
            $trait,
            $clone_box_name,
            { $($rest)* },
            {
                $($impls)*
                fn $method< $($lt),+ >(&self, $($arg: $ty),*) -> $ret {
                    self.as_ref().$method($($arg),*)
                }
            }
        }
    };

    // Munch a `ref fn`
    (
        @impl,
        $trait:ident,
        $clone_box_name:ident,
        {
            ref fn $method:ident(&self, $($arg:ident: $ty:ty),*) -> $ret:ty;
            $($rest:tt)*
        },
        { $($impls:tt)* }
    ) => {
        impl_trait_for_box! {
            @impl,
            $trait,
            $clone_box_name,
            { $($rest)* },
            {
                $($impls)*
                fn $method(&self, $($arg: $ty),*) -> $ret {
                    self.as_ref().$method($($arg),*)
                }
            }
        }
    };

    // Munch a `self fn` with custom implementation
    (
        @impl,
        $trait:ident,
        $clone_box_name:ident,
        {
            self fn $method:ident(self, $($arg:ident: $ty:ty),*) -> $ret:ty { $($body:tt)+ };
            $($rest:tt)*
        },
        { $($impls:tt)* }
    ) => {
        impl_trait_for_box! {
            @impl,
            $trait,
            $clone_box_name,
            { $($rest)* },
            {
                $($impls)*
                fn $method(self, $($arg: $ty),*) -> $ret {
                    $($body)+
                }
            }
        }
    };

    // Munch a `self fn` with default `self` return
    (
        @impl,
        $trait:ident,
        $clone_box_name:ident,
        {
            self fn $method:ident(self, $($arg:ident: $ty:ty),*) -> $ret:ty;
            $($rest:tt)*
        },
        { $($impls:tt)* }
    ) => {
        impl_trait_for_box! {
            @impl,
            $trait,
            $clone_box_name,
            { $($rest)* },
            {
                $($impls)*
                fn $method(self, $($arg: $ty),*) -> $ret {
                    self
                }
            }
        }
    };

    // Public entry point
    ($trait:ident { $($methods:tt)* }, $clone_box_name:ident) => {
        impl_trait_for_box! {
            @impl,
            $trait,
            $clone_box_name,
            { $($methods)* },
            { }
        }
    };
}

/// Trait for aead encryption algorithms with Authenticated Encryption with Associated Data (AEAD).
///
/// 用于带关联数据认证加密 (AEAD) 的对称加密算法 trait。
///
/// ## Overview | 概述
///
/// This trait provides a unified interface for aead encryption algorithms that support
/// AEAD (Authenticated Encryption with Associated Data). All methods are object-safe,
/// allowing the trait to be used as a trait object.
///
/// 此 trait 为支持 AEAD(带关联数据的认证加密)的对称加密算法提供统一接口。
/// 所有方法都是对象安全的,允许将 trait 用作 trait 对象。
///
/// ## Supported Algorithms | 支持的算法
///
/// - AES-128-GCM, AES-256-GCM
/// - ChaCha20-Poly1305, XChaCha20-Poly1305
///
/// ## Security Guarantees | 安全保证
///
/// - **Confidentiality**: Plaintext is encrypted and cannot be recovered without the key
/// - **Authenticity**: Ciphertext integrity is verified during decryption
/// - **Associated Data**: Additional data can be authenticated without encryption
///
/// - **机密性**: 明文被加密,没有密钥无法恢复
/// - **真实性**: 解密时验证密文完整性
/// - **关联数据**: 可以在不加密的情况下认证附加数据
///
/// ## Usage Guidelines | 使用指南
///
/// - Always use a unique nonce for each encryption operation
/// - Never reuse nonce-key pairs
/// - Use cryptographically secure random number generation for nonces
/// - Consider using associated data for context binding
///
/// - 每次加密操作都使用唯一的 nonce
/// - 永远不要重复使用 nonce-密钥对
/// - 为 nonce 使用密码学安全的随机数生成
/// - 考虑使用关联数据进行上下文绑定
#[cfg(feature = "aead")]
pub trait AeadAlgorithmTrait: Send + Sync + 'static + std::fmt::Debug {
    /// Encrypts plaintext with optional associated data.
    ///
    /// 使用可选关联数据加密明文。
    ///
    /// # Arguments | 参数
    ///
    /// * `key` - Typed aead key bound to this algorithm | 绑定到此算法的类型化对称密钥
    /// * `plaintext` - Data to encrypt | 要加密的数据
    /// * `nonce` - Unique number used once (must be unique per key) | 一次性使用的唯一数字(每个密钥必须唯一)
    /// * `aad` - Optional associated data to authenticate | 要认证的可选关联数据
    ///
    /// # Returns | 返回值
    ///
    /// Encrypted ciphertext with authentication tag appended.
    ///
    /// 附加了认证标签的加密密文。
    ///
    /// # Errors | 错误
    ///
    /// - Key algorithm mismatch | 密钥算法不匹配
    /// - Invalid nonce length | 无效的 nonce 长度
    /// - Encryption failure | 加密失败
    ///
    /// # Security | 安全性
    ///
    /// The nonce MUST be unique for each encryption with the same key.
    /// Reusing nonces can lead to catastrophic security failures.
    ///
    /// 对于同一密钥的每次加密,nonce 必须是唯一的。
    /// 重复使用 nonce 可能导致灾难性的安全故障。
    fn encrypt(
        &self,
        plaintext: &[u8],
        key: &TypedAeadKey,
        nonce: &[u8],
        aad: Option<&[u8]>,
    ) -> Result<Vec<u8>>;

    /// Encrypts plaintext into a provided buffer.
    ///
    /// 将明文加密到提供的缓冲区中。
    ///
    /// This is a zero-allocation variant of `encrypt` that writes directly
    /// to the provided output buffer.
    ///
    /// 这是 `encrypt` 的零分配变体,直接写入提供的输出缓冲区。
    ///
    /// # Arguments | 参数
    ///
    /// * `output` - Buffer to write encrypted data (must be large enough) | 写入加密数据的缓冲区(必须足够大)
    ///
    /// # Returns | 返回值
    ///
    /// Number of bytes written to the output buffer.
    ///
    /// 写入输出缓冲区的字节数。
    fn encrypt_to_buffer(
        &self,
        plaintext: &[u8],
        output: &mut [u8],
        key: &TypedAeadKey,
        nonce: &[u8],
        aad: Option<&[u8]>,
    ) -> Result<usize>;

    /// Decrypts ciphertext and verifies authentication.
    ///
    /// 解密密文并验证认证。
    ///
    /// # Arguments | 参数
    /// * `ciphertext` - Encrypted data with authentication tag | 带认证标签的加密数据
    /// * `key` - Typed aead key bound to this algorithm | 绑定到此算法的类型化对称密钥
    /// * `nonce` - Same nonce used for encryption | 用于加密的相同 nonce
    /// * `aad` - Same associated data used for encryption | 用于加密的相同关联数据
    ///
    /// # Returns | 返回值
    ///
    /// Decrypted plaintext if authentication succeeds.
    ///
    /// 如果认证成功则返回解密的明文。
    ///
    /// # Errors | 错误
    ///
    /// - Key algorithm mismatch | 密钥算法不匹配
    /// - Authentication failure (tampered data) | 认证失败(数据被篡改)
    /// - Invalid ciphertext format | 无效的密文格式
    ///
    /// # Security | 安全性
    ///
    /// Authentication failure indicates the ciphertext has been tampered with
    /// or the wrong key/nonce/AAD was used. Never use unauthenticated data.
    ///
    /// 认证失败表示密文已被篡改或使用了错误的密钥/nonce/AAD。
    /// 永远不要使用未经认证的数据。
    fn decrypt(
        &self,
        ciphertext: &[u8],
        key: &TypedAeadKey,
        nonce: &[u8],
        aad: Option<&[u8]>,
    ) -> Result<Vec<u8>>;

    /// Decrypts ciphertext into a provided buffer.
    ///
    /// 将密文解密到提供的缓冲区中。
    ///
    /// Zero-allocation variant of `decrypt` that writes directly to the output buffer.
    ///
    /// `decrypt` 的零分配变体,直接写入输出缓冲区。
    ///
    /// # Returns | 返回值
    ///
    /// Number of bytes written to the output buffer.
    ///
    /// 写入输出缓冲区的字节数。
    fn decrypt_to_buffer(
        &self,
        ciphertext: &[u8],
        output: &mut [u8],
        key: &TypedAeadKey,
        nonce: &[u8],
        aad: Option<&[u8]>,
    ) -> Result<usize>;

    /// Generates a new typed aead key for this algorithm.
    ///
    /// 为此算法生成新的类型化对称密钥。
    ///
    /// The generated key is cryptographically bound to this specific algorithm
    /// and cannot be used with other algorithms.
    ///
    /// 生成的密钥在密码学上绑定到此特定算法,不能与其他算法一起使用。
    ///
    /// # Returns | 返回值
    ///
    /// A new typed aead key with proper algorithm binding.
    ///
    /// 具有正确算法绑定的新类型化对称密钥。
    fn generate_typed_key(&self) -> Result<TypedAeadKey>;

    /// Generates a new untyped aead key.
    ///
    /// 生成新的非类型化对称密钥。
    ///
    /// This generates raw key material without algorithm binding.
    /// Use `generate_typed_key` for type-safe operations.
    ///
    /// 这生成没有算法绑定的原始密钥材料。
    /// 使用 `generate_typed_key` 进行类型安全操作。
    fn generate_untyped_key(&self) -> Result<UntypedAeadKey>;

    /// Returns the algorithm identifier.
    ///
    /// 返回算法标识符。
    ///
    /// Used for runtime algorithm verification and key compatibility checking.
    ///
    /// 用于运行时算法验证和密钥兼容性检查。
    fn algorithm(&self) -> AeadAlgorithm;

    /// Returns the key size in bytes for this algorithm.
    ///
    /// 返回此算法的密钥大小(字节)。
    ///
    /// # Examples | 示例
    ///
    /// - AES-128: 16 bytes
    /// - AES-256: 32 bytes
    /// - ChaCha20: 32 bytes
    fn key_size(&self) -> usize;

    /// Returns the nonce size in bytes for this algorithm.
    ///
    /// 返回此算法的 nonce 大小(字节)。
    ///
    /// # Examples | 示例
    ///
    /// - AES-GCM: 12 bytes (96 bits)
    /// - ChaCha20-Poly1305: 12 bytes
    /// - XChaCha20-Poly1305: 24 bytes
    fn nonce_size(&self) -> usize;

    /// Returns the authentication tag size in bytes.
    ///
    /// 返回认证标签大小(字节)。
    ///
    /// All supported AEAD algorithms use 16-byte (128-bit) tags.
    ///
    /// 所有支持的 AEAD 算法都使用 16 字节(128 位)标签。
    fn tag_size(&self) -> usize;

    /// Converts the algorithm into a boxed trait object.
    ///
    /// 将算法转换为 boxed trait 对象。
    ///
    /// Consumes `self` and returns a heap-allocated trait object.
    /// Useful for storing different algorithm types in collections.
    ///
    /// 消费 `self` 并返回堆分配的 trait 对象。
    /// 用于在集合中存储不同的算法类型。
    fn into_boxed(self) -> Box<dyn AeadAlgorithmTrait>;

    /// Creates a cloned boxed trait object.
    ///
    /// 创建克隆的 boxed trait 对象。
    ///
    /// Returns a new heap-allocated trait object with the same algorithm.
    /// Required for implementing `Clone` on `Box<dyn AeadAlgorithmTrait>`.
    ///
    /// 返回具有相同算法的新堆分配 trait 对象。
    /// 在 `Box<dyn AeadAlgorithmTrait>` 上实现 `Clone` 所必需的。
    fn clone_box(&self) -> Box<dyn AeadAlgorithmTrait>;
}

#[cfg(feature = "aead")]
impl_trait_for_box!(AeadAlgorithmTrait {
    ref fn encrypt(&self, plaintext: &[u8], key: &TypedAeadKey, nonce: &[u8], aad: Option<&[u8]>) -> Result<Vec<u8>>;
    ref fn encrypt_to_buffer(&self, plaintext: &[u8], output: &mut [u8], key: &TypedAeadKey, nonce: &[u8], aad: Option<&[u8]>) -> Result<usize>;
    ref fn decrypt(&self, ciphertext: &[u8], key: &TypedAeadKey, nonce: &[u8], aad: Option<&[u8]>) -> Result<Vec<u8>>;
    ref fn decrypt_to_buffer(&self, ciphertext: &[u8], output: &mut [u8], key: &TypedAeadKey, nonce: &[u8], aad: Option<&[u8]>) -> Result<usize>;
    ref fn generate_typed_key(&self,) -> Result<TypedAeadKey>;
    ref fn generate_untyped_key(&self,) -> Result<UntypedAeadKey>;
    ref fn algorithm(&self,) -> AeadAlgorithm;
    ref fn key_size(&self,) -> usize;
    ref fn nonce_size(&self,) -> usize;
    ref fn tag_size(&self,) -> usize;
    self fn into_boxed(self,) -> Box<dyn AeadAlgorithmTrait>;
    ref fn clone_box(&self,) -> Box<dyn AeadAlgorithmTrait>;
}, clone_box);

/// Trait to provide the details for a specific asymmetric algorithm.
/// The implementor of this trait is the scheme itself.
///
/// 用于提供特定非对称算法详细信息的 trait。
/// 该 trait 的实现者是算法方案本身。
#[cfg(feature = "asymmetric-kem")]
pub trait KemAlgorithmTrait: Send + Sync + 'static + std::fmt::Debug {
    /// Returns the algorithm enum.
    ///
    /// 返回算法枚举。
    fn algorithm(&self) -> KemAlgorithm;

    /// Encapsulates a key.
    ///
    /// 封装一个密钥。
    fn encapsulate_key(
        &self,
        public_key: &TypedKemPublicKey,
    ) -> Result<(SharedSecret, EncapsulatedKey)>;

    /// Decapsulates a key.
    ///
    /// 解封装一个密钥。
    fn decapsulate_key(
        &self,
        private_key: &TypedKemPrivateKey,
        encapsulated_key: &EncapsulatedKey,
    ) -> Result<SharedSecret>;

    fn generate_keypair(&self) -> Result<TypedKemKeyPair>;

    /// Clones the algorithm.
    ///
    /// 克隆算法。
    fn clone_box(&self) -> Box<dyn KemAlgorithmTrait>;

    fn into_boxed(self) -> Box<dyn KemAlgorithmTrait>;
}

#[cfg(feature = "asymmetric-kem")]
impl_trait_for_box!(KemAlgorithmTrait {
    ref fn clone_box(&self,) -> Box<dyn KemAlgorithmTrait>;
    ref fn algorithm(&self,) -> KemAlgorithm;
    ref fn encapsulate_key(&self, public_key: &TypedKemPublicKey) -> Result<(SharedSecret, EncapsulatedKey)>;
    ref fn decapsulate_key(&self, private_key: &TypedKemPrivateKey, encapsulated_key: &EncapsulatedKey) -> Result<SharedSecret>;
    ref fn generate_keypair(&self,) -> Result<TypedKemKeyPair>;
    self fn into_boxed(self,) -> Box<dyn KemAlgorithmTrait>;
}, clone_box);

#[cfg(feature = "kdf")]
pub trait KdfKeyAlgorithmTrait: Send + Sync + 'static + std::fmt::Debug {
    fn derive(
        &self,
        ikm: &[u8],
        salt: Option<&[u8]>,
        info: Option<&[u8]>,
        output_len: usize,
    ) -> Result<Zeroizing<Vec<u8>>>;

    fn algorithm(&self) -> KdfKeyAlgorithm;

    fn clone_box(&self) -> Box<dyn KdfKeyAlgorithmTrait>;

    fn into_boxed(self) -> Box<dyn KdfKeyAlgorithmTrait>;
}

#[cfg(feature = "kdf")]
impl_trait_for_box!(KdfKeyAlgorithmTrait {
    ref fn clone_box(&self,) -> Box<dyn KdfKeyAlgorithmTrait>;
    ref fn derive(&self, ikm: &[u8], salt: Option<&[u8]>, info: Option<&[u8]>, output_len: usize) -> Result<Zeroizing<Vec<u8>>>;
    ref fn algorithm(&self,) -> KdfKeyAlgorithm;
    self fn into_boxed(self,) -> Box<dyn KdfKeyAlgorithmTrait>;
}, clone_box);

#[cfg(feature = "kdf")]
pub trait KdfPasswordAlgorithmTrait: Send + Sync + 'static + std::fmt::Debug {
    fn derive(
        &self,
        password: &SecretBox<[u8]>,
        salt: &[u8],
        output_len: usize,
    ) -> Result<Zeroizing<Vec<u8>>>;

    fn algorithm(&self) -> KdfPasswordAlgorithm;

    fn clone_box(&self) -> Box<dyn KdfPasswordAlgorithmTrait>;

    fn into_boxed(self) -> Box<dyn KdfPasswordAlgorithmTrait>;
}

#[cfg(feature = "kdf")]
impl_trait_for_box!(KdfPasswordAlgorithmTrait {
    ref fn clone_box(&self,) -> Box<dyn KdfPasswordAlgorithmTrait>;
    ref fn derive(&self, password: &SecretBox<[u8]>, salt: &[u8], output_len: usize) -> Result<Zeroizing<Vec<u8>>>;
    ref fn algorithm(&self,) -> KdfPasswordAlgorithm;
    self fn into_boxed(self,) -> Box<dyn KdfPasswordAlgorithmTrait>;
}, clone_box);

#[cfg(feature = "xof")]
pub trait XofAlgorithmTrait: Send + Sync + 'static + std::fmt::Debug {
    fn reader<'a>(
        &self,
        ikm: &'a [u8],
        salt: Option<&'a [u8]>,
        info: Option<&'a [u8]>,
    ) -> Result<XofReaderWrapper<'a>>;
    fn clone_box(&self) -> Box<dyn XofAlgorithmTrait>;
    fn algorithm(&self) -> XofAlgorithm;

    fn into_boxed(self) -> Box<dyn XofAlgorithmTrait>;
}

#[cfg(feature = "xof")]
impl_trait_for_box!(XofAlgorithmTrait {
    ref fn reader<'a>(&self, ikm: &'a [u8], salt: Option<&'a [u8]>, info: Option<&'a [u8]>) -> Result<XofReaderWrapper<'a>>;
    ref fn algorithm(&self,) -> XofAlgorithm;
    ref fn clone_box(&self,) -> Box<dyn XofAlgorithmTrait>;
    self fn into_boxed(self,) -> Box<dyn XofAlgorithmTrait>;
}, clone_box);

#[cfg(feature = "asymmetric-signature")]
pub trait SignatureAlgorithmTrait: Send + Sync + 'static + std::fmt::Debug {
    fn sign(&self, message: &[u8], key: &TypedSignaturePrivateKey) -> Result<SignatureWrapper>;
    fn verify(
        &self,
        message: &[u8],
        key: &TypedSignaturePublicKey,
        signature: &SignatureWrapper,
    ) -> Result<()>;
    fn generate_keypair(&self) -> Result<TypedSignatureKeyPair>;
    fn clone_box(&self) -> Box<dyn SignatureAlgorithmTrait>;
    fn algorithm(&self) -> SignatureAlgorithm;

    fn into_boxed(self) -> Box<dyn SignatureAlgorithmTrait>;
}

#[cfg(feature = "asymmetric-signature")]
impl_trait_for_box!(SignatureAlgorithmTrait {
    ref fn sign(&self, message: &[u8], key: &TypedSignaturePrivateKey) -> Result<SignatureWrapper>;
    ref fn verify(&self, message: &[u8], key: &TypedSignaturePublicKey, signature: &SignatureWrapper) -> Result<()>;
    ref fn generate_keypair(&self,) -> Result<TypedSignatureKeyPair>;
    ref fn clone_box(&self,) -> Box<dyn SignatureAlgorithmTrait>;
    ref fn algorithm(&self,) -> SignatureAlgorithm;
    self fn into_boxed(self,) -> Box<dyn SignatureAlgorithmTrait>;
}, clone_box);

#[cfg(feature = "asymmetric-key-agreement")]
pub trait KeyAgreementAlgorithmTrait: Send + Sync + 'static + std::fmt::Debug {
    fn agree(
        &self,
        sk: &TypedKeyAgreementPrivateKey,
        pk: &TypedKeyAgreementPublicKey,
    ) -> Result<Zeroizing<Vec<u8>>>;
    fn generate_keypair(&self) -> Result<TypedKeyAgreementKeyPair>;
    fn clone_box(&self) -> Box<dyn KeyAgreementAlgorithmTrait>;
    fn algorithm(&self) -> KeyAgreementAlgorithm;

    fn into_boxed(self) -> Box<dyn KeyAgreementAlgorithmTrait>;
}

#[cfg(feature = "asymmetric-key-agreement")]
impl_trait_for_box!(KeyAgreementAlgorithmTrait {
    ref fn agree(&self, sk: &TypedKeyAgreementPrivateKey, pk: &TypedKeyAgreementPublicKey) -> Result<Zeroizing<Vec<u8>>>;
    ref fn generate_keypair(&self,) -> Result<TypedKeyAgreementKeyPair>;
    ref fn clone_box(&self,) -> Box<dyn KeyAgreementAlgorithmTrait>;
    ref fn algorithm(&self,) -> KeyAgreementAlgorithm;
    self fn into_boxed(self,) -> Box<dyn KeyAgreementAlgorithmTrait>;
}, clone_box);

pub trait HashAlgorithmTrait: Send + Sync + 'static + std::fmt::Debug {
    /// Hashes the given data.
    ///
    /// 哈希给定的数据。
    fn hash(&self, data: &[u8]) -> Vec<u8>;

    /// Computes the HMAC of a message using the given key.
    ///
    /// 使用给定的密钥计算消息的 HMAC。
    fn hmac(&self, key: &[u8], msg: &[u8]) -> Result<Vec<u8>>;

    /// Returns the algorithm enum.
    ///
    /// 返回算法枚举。
    fn algorithm(&self) -> HashAlgorithm;

    /// Clones the algorithm.
    ///
    /// 克隆算法。
    fn clone_box(&self) -> Box<dyn HashAlgorithmTrait>;

    fn into_boxed(self) -> Box<dyn HashAlgorithmTrait>;
}

impl_trait_for_box!(HashAlgorithmTrait {
    ref fn hash(&self, data: &[u8]) -> Vec<u8>;
    ref fn hmac(&self, key: &[u8], msg: &[u8]) -> Result<Vec<u8>>;
    ref fn algorithm(&self,) -> HashAlgorithm;
    ref fn clone_box(&self,) -> Box<dyn HashAlgorithmTrait>;
    self fn into_boxed(self,) -> Box<dyn HashAlgorithmTrait>;
}, clone_box);