seal_crypto_wrapper/algorithms/xof.rs
1//! Extendable Output Functions (XOF) for variable-length cryptographic output.
2//!
3//! 用于可变长度密码输出的可扩展输出函数 (XOF)。
4//!
5//! ## Overview | 概述
6//!
7//! Extendable Output Functions (XOFs) are cryptographic functions that can produce
8//! output of any desired length. Unlike traditional hash functions with fixed output
9//! sizes, XOFs can generate arbitrarily long pseudorandom sequences from input data.
10//!
11//! 可扩展输出函数 (XOF) 是可以产生任何所需长度输出的密码函数。
12//! 与具有固定输出大小的传统哈希函数不同,XOF 可以从输入数据生成任意长的伪随机序列。
13//!
14//! ## Use Cases | 使用场景
15//!
16//! - **Key Derivation**: Generate keys of specific lengths
17//! - **Random Number Generation**: Produce cryptographically secure random data
18//! - **Stream Ciphers**: Create keystreams for encryption
19//! - **Mask Generation**: Generate masks for cryptographic protocols
20//! - **Domain Separation**: Create distinct outputs for different contexts
21//!
22//! - **密钥派生**: 生成特定长度的密钥
23//! - **随机数生成**: 产生密码学安全的随机数据
24//! - **流密码**: 为加密创建密钥流
25//! - **掩码生成**: 为密码协议生成掩码
26//! - **域分离**: 为不同上下文创建不同的输出
27//!
28//! ## SHAKE Algorithm Family | SHAKE 算法族
29//!
30//! SHAKE functions are based on the Keccak sponge construction (same as SHA-3)
31//! but with extendable output capability:
32//!
33//! SHAKE 函数基于 Keccak 海绵构造(与 SHA-3 相同),但具有可扩展输出能力:
34//!
35//! | Algorithm | Security Level | Rate | Capacity | Use Case |
36//! |-----------|----------------|------|----------|----------|
37//! | SHAKE-128 | 128-bit | 1344 bits | 256 bits | General purpose |
38//! | SHAKE-256 | 256-bit | 1088 bits | 512 bits | High security |
39//!
40//! ## Security Properties | 安全属性
41//!
42//! - **Pseudorandomness**: Output is indistinguishable from random
43//! - **Collision Resistance**: Infeasible to find two inputs with same output
44//! - **Preimage Resistance**: Given output, infeasible to find input
45//! - **Domain Separation**: Different contexts produce independent outputs
46//!
47//! - **伪随机性**: 输出与随机数据无法区分
48//! - **抗碰撞性**: 找到具有相同输出的两个输入在计算上不可行
49//! - **原像抗性**: 给定输出,找到输入在计算上不可行
50//! - **域分离**: 不同上下文产生独立的输出
51
52use crate::bincode::{Decode, Encode};
53
54/// Extendable Output Function algorithm enumeration.
55///
56/// 可扩展输出函数算法枚举。
57///
58/// ## Algorithm Selection | 算法选择
59///
60/// Choose based on your security requirements:
61/// - **SHAKE-128**: For general-purpose applications requiring 128-bit security
62/// - **SHAKE-256**: For high-security applications requiring 256-bit security
63///
64/// 根据您的安全要求选择:
65/// - **SHAKE-128**: 用于需要 128 位安全性的通用应用
66/// - **SHAKE-256**: 用于需要 256 位安全性的高安全性应用
67#[derive(
68 Debug, Clone, Copy, PartialEq, Eq, Hash, Decode, Encode, serde::Serialize, serde::Deserialize,
69)]
70pub enum XofAlgorithm {
71 /// SHAKE family of extendable output functions.
72 ///
73 /// SHAKE 可扩展输出函数族。
74 ///
75 /// Based on the Keccak sponge construction, providing variable-length output
76 /// with strong security guarantees. Standardized in FIPS 202.
77 ///
78 /// 基于 Keccak 海绵构造,提供具有强安全保证的可变长度输出。
79 /// 在 FIPS 202 中标准化。
80 Shake(ShakeVariant),
81}
82
83/// SHAKE algorithm variants with different security levels.
84///
85/// 具有不同安全级别的 SHAKE 算法变体。
86///
87/// ## Performance vs Security | 性能与安全性
88///
89/// SHAKE-128 offers better performance while SHAKE-256 provides higher security.
90/// Both are suitable for most applications, with the choice depending on
91/// specific security requirements.
92///
93/// SHAKE-128 提供更好的性能,而 SHAKE-256 提供更高的安全性。
94/// 两者都适用于大多数应用,选择取决于特定的安全要求。
95#[derive(
96 Debug, Clone, Copy, PartialEq, Eq, Hash, Decode, Encode, serde::Serialize, serde::Deserialize,
97)]
98pub enum ShakeVariant {
99 /// SHAKE-128: 128-bit security level.
100 ///
101 /// SHAKE-128: 128 位安全级别。
102 ///
103 /// ## Properties | 属性
104 /// - Security level: 128-bit
105 /// - Rate: 1344 bits (168 bytes)
106 /// - Capacity: 256 bits (32 bytes)
107 /// - Performance: High
108 ///
109 /// ## Use Cases | 使用场景
110 /// Suitable for most applications requiring variable-length output.
111 /// Recommended for general-purpose key derivation and random generation.
112 ///
113 /// 适用于大多数需要可变长度输出的应用。
114 /// 推荐用于通用密钥派生和随机生成。
115 V128,
116
117 /// SHAKE-256: 256-bit security level.
118 ///
119 /// SHAKE-256: 256 位安全级别。
120 ///
121 /// ## Properties | 属性
122 /// - Security level: 256-bit
123 /// - Rate: 1088 bits (136 bytes)
124 /// - Capacity: 512 bits (64 bytes)
125 /// - Performance: Medium
126 ///
127 /// ## Use Cases | 使用场景
128 /// For applications requiring higher security margins or long-term protection.
129 /// Recommended for high-value or sensitive applications.
130 ///
131 /// 用于需要更高安全边际或长期保护的应用。
132 /// 推荐用于高价值或敏感应用。
133 V256,
134}
135
136impl XofAlgorithm {
137 /// Creates a new XOF algorithm builder.
138 ///
139 /// 创建新的 XOF 算法构建器。
140 ///
141 /// ## Examples | 示例
142 ///
143 /// ```rust
144 /// use seal_crypto_wrapper::algorithms::xof::XofAlgorithm;
145 ///
146 /// let shake128 = XofAlgorithm::build().shake128();
147 /// let shake256 = XofAlgorithm::build().shake256();
148 /// ```
149 pub fn build() -> XofAlgorithmBuilder {
150 XofAlgorithmBuilder
151 }
152}
153
154/// Builder for constructing XOF algorithm instances.
155///
156/// 用于构建 XOF 算法实例的构建器。
157///
158/// ## Usage Pattern | 使用模式
159///
160/// ```rust
161/// use seal_crypto_wrapper::algorithms::xof::XofAlgorithm;
162///
163/// // For general-purpose applications
164/// let shake128 = XofAlgorithm::build().shake128();
165///
166/// // For high-security applications
167/// let shake256 = XofAlgorithm::build().shake256();
168/// ```
169///
170/// ## Performance Considerations | 性能考虑
171///
172/// SHAKE-128 is faster due to its higher rate (more data processed per round),
173/// while SHAKE-256 provides higher security at the cost of some performance.
174///
175/// SHAKE-128 由于其更高的速率(每轮处理更多数据)而更快,
176/// 而 SHAKE-256 以一些性能为代价提供更高的安全性。
177pub struct XofAlgorithmBuilder;
178
179impl XofAlgorithmBuilder {
180 /// Selects SHAKE-128 extendable output function.
181 ///
182 /// 选择 SHAKE-128 可扩展输出函数。
183 ///
184 /// ## Properties | 属性
185 /// - Security level: 128-bit
186 /// - Rate: 1344 bits (168 bytes per round)
187 /// - Capacity: 256 bits
188 /// - Performance: High
189 ///
190 /// ## Use Cases | 使用场景
191 /// - General-purpose key derivation
192 /// - Random number generation
193 /// - Stream cipher keystreams
194 /// - Mask generation functions
195 ///
196 /// - 通用密钥派生
197 /// - 随机数生成
198 /// - 流密码密钥流
199 /// - 掩码生成函数
200 ///
201 /// ## Examples | 示例
202 ///
203 /// ```rust
204 /// use seal_crypto_wrapper::algorithms::xof::XofAlgorithm;
205 /// use seal_crypto_wrapper::prelude::XofAlgorithmTrait;
206 ///
207 /// let xof = XofAlgorithm::build().shake128();
208 /// let wrapper = xof.into_wrapper();
209 ///
210 /// // Generate variable-length output
211 /// let mut reader = wrapper.reader(b"input data", None, None)?;
212 /// let output = reader.read_boxed(32); // 32 bytes of output
213 /// # Ok::<(), Box<dyn std::error::Error>>(())
214 /// ```
215 pub fn shake128(self) -> XofAlgorithm {
216 XofAlgorithm::Shake(ShakeVariant::V128)
217 }
218
219 /// Selects SHAKE-256 extendable output function.
220 ///
221 /// 选择 SHAKE-256 可扩展输出函数。
222 ///
223 /// ## Properties | 属性
224 /// - Security level: 256-bit
225 /// - Rate: 1088 bits (136 bytes per round)
226 /// - Capacity: 512 bits
227 /// - Performance: Medium
228 ///
229 /// ## Use Cases | 使用场景
230 /// - High-security key derivation
231 /// - Long-term cryptographic applications
232 /// - Post-quantum security preparations
233 /// - High-value data protection
234 ///
235 /// - 高安全性密钥派生
236 /// - 长期密码应用
237 /// - 后量子安全准备
238 /// - 高价值数据保护
239 ///
240 /// ## Examples | 示例
241 ///
242 /// ```rust
243 /// use seal_crypto_wrapper::algorithms::xof::XofAlgorithm;
244 /// use seal_crypto_wrapper::prelude::XofAlgorithmTrait;
245 ///
246 /// let xof = XofAlgorithm::build().shake256();
247 /// let wrapper = xof.into_wrapper();
248 ///
249 /// // Generate large amounts of pseudorandom data
250 /// let mut reader = wrapper.reader(b"seed", Some(b"salt"), Some(b"info"))?;
251 /// let large_output = reader.read_boxed(1024); // 1KB of output
252 /// # Ok::<(), Box<dyn std::error::Error>>(())
253 /// ```
254 pub fn shake256(self) -> XofAlgorithm {
255 XofAlgorithm::Shake(ShakeVariant::V256)
256 }
257}
258
259use crate::wrappers::xof::XofWrapper;
260
261impl XofAlgorithm {
262 /// Converts the algorithm enum into a concrete wrapper implementation.
263 ///
264 /// 将算法枚举转换为具体的包装器实现。
265 ///
266 /// ## Purpose | 目的
267 ///
268 /// This method creates a wrapper that implements the XOF algorithm trait,
269 /// enabling actual cryptographic operations with variable-length output
270 /// generation capabilities.
271 ///
272 /// 此方法创建一个实现 XOF 算法 trait 的包装器,
273 /// 启用具有可变长度输出生成能力的实际密码操作。
274 ///
275 /// ## Returns | 返回值
276 ///
277 /// An `XofWrapper` that can:
278 /// - Create readers for streaming output
279 /// - Generate arbitrary-length pseudorandom data
280 /// - Support domain separation with salt and info parameters
281 /// - Provide algorithm introspection
282 ///
283 /// 可以执行以下操作的 `XofWrapper`:
284 /// - 为流式输出创建读取器
285 /// - 生成任意长度的伪随机数据
286 /// - 支持使用盐和信息参数的域分离
287 /// - 提供算法内省
288 ///
289 /// ## Examples | 示例
290 ///
291 /// ```rust
292 /// use seal_crypto_wrapper::algorithms::xof::XofAlgorithm;
293 /// use seal_crypto_wrapper::prelude::XofAlgorithmTrait;
294 ///
295 /// let algorithm = XofAlgorithm::build().shake128();
296 /// let xof = algorithm.into_wrapper();
297 ///
298 /// // Create a reader with input key material
299 /// let mut reader = xof.reader(
300 /// b"input_key_material",
301 /// Some(b"optional_salt"),
302 /// Some(b"context_info")
303 /// )?;
304 ///
305 /// // Read different amounts of data
306 /// let key1 = reader.read_boxed(32); // 32-byte key
307 /// let key2 = reader.read_boxed(16); // 16-byte key
308 /// let nonce = reader.read_boxed(12); // 12-byte nonce
309 /// # Ok::<(), Box<dyn std::error::Error>>(())
310 /// ```
311 pub fn into_wrapper(self) -> XofWrapper {
312 use crate::wrappers::xof::{Shake128Wrapper, Shake256Wrapper};
313 match self {
314 XofAlgorithm::Shake(ShakeVariant::V128) => {
315 XofWrapper::new(Box::new(Shake128Wrapper::default()))
316 }
317 XofAlgorithm::Shake(ShakeVariant::V256) => {
318 XofWrapper::new(Box::new(Shake256Wrapper::default()))
319 }
320 }
321 }
322}