ciphern 0.2.1

Enterprise-grade cryptographic library
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
// Copyright (c) 2025 Kirky.X
//
// Licensed under the MIT License
// See LICENSE file in the project root for full license information.

use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Mutex;
use std::time::{Duration, Instant};

use crate::error::Result;
use crate::random::SecureRandom;

// === Struct Definitions ===

/// 嵌入式功耗分析防护配置
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct EmbeddedPowerConfig {
    /// 是否启用ARM Cortex-M特定优化
    pub cortex_m_optimization: bool,
    /// 功耗掩码强度 (0.0 - 1.0)
    pub power_masking_strength: f32,
    /// 随机延迟范围(微秒)
    pub random_delay_range_us: (u32, u32),
    /// 是否启用时钟抖动
    pub clock_jitter_enabled: bool,
    /// 时钟抖动强度 (0.0 - 1.0)
    pub clock_jitter_strength: f32,
    /// 是否启用功耗噪声注入
    pub power_noise_injection: bool,
    /// 功耗噪声强度 (0.0 - 1.0)
    pub power_noise_strength: f32,
}

/// 嵌入式功耗分析防护器
#[allow(dead_code)]
pub struct EmbeddedPowerProtector {
    pub(crate) config: EmbeddedPowerConfig,
    pub(crate) operation_counter: AtomicU32,
    pub(crate) last_operation_time: Mutex<Option<Instant>>,
}

/// 嵌入式功耗防护统计信息
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct EmbeddedPowerStats {
    /// 总操作次数
    pub total_operations: u32,
    /// 最后一次操作时间
    pub last_operation_time: Option<Instant>,
    /// 是否启用Cortex-M优化
    pub cortex_m_optimization_enabled: bool,
    /// 功耗掩码强度
    pub power_masking_strength: f32,
}

/// 嵌入式功耗防护构建器
#[allow(dead_code)]
pub struct EmbeddedPowerProtectorBuilder {
    pub(crate) config: EmbeddedPowerConfig,
}

// === Implementation: EmbeddedPowerConfig ===

impl Default for EmbeddedPowerConfig {
    /// 创建默认配置
    fn default() -> Self {
        Self {
            cortex_m_optimization: cfg!(target_arch = "arm"),
            power_masking_strength: 0.8,
            random_delay_range_us: (10, 100),
            clock_jitter_enabled: true,
            clock_jitter_strength: 0.3,
            power_noise_injection: true,
            power_noise_strength: 0.5,
        }
    }
}

// === Implementation: EmbeddedPowerProtector ===

impl EmbeddedPowerProtector {
    /// 创建新的嵌入式功耗防护器
    pub fn new(config: EmbeddedPowerConfig) -> Self {
        Self {
            config,
            operation_counter: AtomicU32::new(0),
            last_operation_time: Mutex::new(None),
        }
    }

    /// 执行功耗分析防护操作
    #[allow(dead_code)]
    pub fn protect_operation<F, R>(&self, operation: F) -> Result<R>
    where
        F: FnOnce() -> Result<R>,
    {
        let start_time = Instant::now();

        self.apply_power_masking()?;
        self.add_random_delay()?;

        if self.config.clock_jitter_enabled {
            self.apply_clock_jitter()?;
        }

        if self.config.power_noise_injection {
            self.inject_power_noise()?;
        }

        let result = operation();
        let operation_time = start_time.elapsed();

        self.operation_counter.fetch_add(1, Ordering::SeqCst);

        {
            let mut last_time = self.last_operation_time.lock().unwrap();
            *last_time = Some(Instant::now());
        }

        self.post_operation_protection(operation_time)?;

        result
    }

    /// 获取统计信息
    #[allow(dead_code)]
    pub fn stats(&self) -> EmbeddedPowerStats {
        let operation_count = self.operation_counter.load(Ordering::SeqCst);
        let last_time = *self.last_operation_time.lock().unwrap();

        EmbeddedPowerStats {
            total_operations: operation_count,
            last_operation_time: last_time,
            cortex_m_optimization_enabled: self.config.cortex_m_optimization,
            power_masking_strength: self.config.power_masking_strength,
        }
    }

    /// 更新配置
    #[allow(dead_code)]
    pub fn set_config(&mut self, config: EmbeddedPowerConfig) {
        self.config = config;
    }

    /// 应用功耗掩码
    fn apply_power_masking(&self) -> Result<()> {
        let masking_strength = self.config.power_masking_strength;

        if self.config.cortex_m_optimization && cfg!(target_arch = "arm") {
            self.apply_cortex_m_masking(masking_strength)?;
        } else {
            self.apply_generic_masking(masking_strength)?;
        }

        Ok(())
    }

    /// ARM Cortex-M特定掩码技术
    fn apply_cortex_m_masking(&self, strength: f32) -> Result<()> {
        let mask_operations = (strength * 100.0) as usize;

        unsafe {
            for _ in 0..mask_operations {
                std::arch::asm!(
                    "nop",
                    "nop",
                    "nop",
                    "nop",
                    options(nostack, preserves_flags)
                );
            }
        }

        self.cortex_m_register_operations(strength)?;

        Ok(())
    }

    /// Cortex-M寄存器操作以创建功耗变化
    #[cfg(target_arch = "arm")]
    fn cortex_m_register_operations(&self, strength: f32) -> Result<()> {
        use core::arch::asm;
        let iterations = (strength * 50.0) as usize;

        unsafe {
            for _ in 0..iterations {
                asm!(
                    "eor r0, r0, r0",
                    "eor r1, r1, r1",
                    "eor r2, r2, r2",
                    "eor r3, r3, r3",
                    options(nostack, preserves_flags)
                );
            }
        }

        Ok(())
    }

    #[cfg(not(target_arch = "arm"))]
    fn cortex_m_register_operations(&self, strength: f32) -> Result<()> {
        let iterations = (strength * 50.0) as usize;

        for i in 0..iterations {
            let mut accumulator = 0u64;
            for j in 0..4 {
                accumulator ^= ((i + j) as u64).wrapping_mul(0x9E3779B9u64);
            }
            std::hint::black_box(accumulator);
        }

        Ok(())
    }

    /// 通用掩码技术
    fn apply_generic_masking(&self, strength: f32) -> Result<()> {
        let mask_operations = (strength * 200.0) as usize;
        let mut mask_data = vec![0u8; mask_operations * 8];

        SecureRandom::new()?.fill(&mut mask_data)?;

        let mut accumulator = 0u64;
        for chunk in mask_data.chunks_exact(8) {
            let value = u64::from_le_bytes(chunk.try_into().unwrap());
            accumulator = accumulator.wrapping_add(value);
            accumulator = accumulator.rotate_left(7);
        }

        std::hint::black_box(accumulator);

        Ok(())
    }

    /// 添加随机延迟
    fn add_random_delay(&self) -> Result<()> {
        let (min_us, max_us) = self.config.random_delay_range_us;
        let delay_range = max_us - min_us;

        if delay_range == 0 {
            if min_us > 0 {
                std::thread::sleep(Duration::from_micros(min_us as u64));
            }
            return Ok(());
        }

        let mut random_bytes = [0u8; 4];
        SecureRandom::new()?.fill(&mut random_bytes)?;

        let random_value = u32::from_le_bytes(random_bytes);
        let delay_us = min_us + (random_value % delay_range);

        if delay_us > 0 {
            std::thread::sleep(Duration::from_micros(delay_us as u64));
        }

        Ok(())
    }

    /// 应用时钟抖动
    fn apply_clock_jitter(&self) -> Result<()> {
        let jitter_strength = self.config.clock_jitter_strength;
        let jitter_operations = (jitter_strength * 100.0) as usize;

        for _ in 0..jitter_operations {
            let start = Instant::now();
            let mut temp = 0u64;

            for i in 0..100 {
                temp = temp.wrapping_add(i as u64);
            }

            let elapsed = start.elapsed();

            if elapsed.as_nanos() < 100 {
                std::thread::sleep(Duration::from_nanos(50));
            }

            std::hint::black_box(temp);
        }

        Ok(())
    }

    /// 注入功耗噪声
    fn inject_power_noise(&self) -> Result<()> {
        let noise_strength = self.config.power_noise_strength;
        let noise_operations = (noise_strength * 150.0) as usize;
        let mut noise_data = vec![0u8; noise_operations * 16];

        SecureRandom::new()?.fill(&mut noise_data)?;

        for chunk in noise_data.chunks_exact(16) {
            let mut accumulator = 0u128;

            for (i, &byte) in chunk.iter().enumerate() {
                accumulator = accumulator.wrapping_add((byte as u128) << (i * 8));
            }

            for _ in 0..10 {
                accumulator = accumulator.wrapping_mul(0x9E3779B97F4A7C15u128);
                accumulator = accumulator.rotate_left(17);
            }

            std::hint::black_box(accumulator);
        }

        Ok(())
    }

    /// 操作后防护
    fn post_operation_protection(&self, operation_time: Duration) -> Result<()> {
        if operation_time.as_micros() < 50 {
            self.add_random_delay()?;
        }

        let mut random_byte = [0u8; 1];
        SecureRandom::new()?.fill(&mut random_byte)?;

        if random_byte[0] % 3 == 0 {
            self.inject_power_noise()?;
        }

        Ok(())
    }
}

// === Implementation: EmbeddedPowerProtectorBuilder ===

impl EmbeddedPowerProtectorBuilder {
    /// 创建新的构建器
    pub fn new() -> Self {
        Self {
            config: EmbeddedPowerConfig::default(),
        }
    }

    /// 设置Cortex-M优化
    #[allow(dead_code)]
    pub fn cortex_m_optimization(mut self, enabled: bool) -> Self {
        self.config.cortex_m_optimization = enabled;
        self
    }

    /// 设置功耗掩码强度
    #[allow(dead_code)]
    pub fn power_masking_strength(mut self, strength: f32) -> Self {
        self.config.power_masking_strength = strength.clamp(0.0, 1.0);
        self
    }

    /// 设置随机延迟范围
    #[allow(dead_code)]
    pub fn random_delay_range(mut self, min_us: u32, max_us: u32) -> Self {
        self.config.random_delay_range_us = (min_us, max_us);
        self
    }

    /// 设置时钟抖动
    #[allow(dead_code)]
    pub fn clock_jitter(mut self, enabled: bool, strength: f32) -> Self {
        self.config.clock_jitter_enabled = enabled;
        self.config.clock_jitter_strength = strength.clamp(0.0, 1.0);
        self
    }

    /// 设置功耗噪声
    #[allow(dead_code)]
    pub fn power_noise(mut self, enabled: bool, strength: f32) -> Self {
        self.config.power_noise_injection = enabled;
        self.config.power_noise_strength = strength.clamp(0.0, 1.0);
        self
    }

    /// 构建防护器
    #[allow(dead_code)]
    pub fn build(self) -> EmbeddedPowerProtector {
        EmbeddedPowerProtector::new(self.config)
    }
}

#[allow(dead_code)]
impl Default for EmbeddedPowerProtectorBuilder {
    fn default() -> Self {
        Self::new()
    }
}

// === Tests ===

#[cfg(test)]
mod tests {
    use super::{EmbeddedPowerConfig, EmbeddedPowerProtector, EmbeddedPowerProtectorBuilder};
    use crate::error::CryptoError;

    #[test]
    fn test_embedded_power_protector_creation() {
        let protector = EmbeddedPowerProtector::new(EmbeddedPowerConfig::default());
        let stats = protector.stats();

        assert_eq!(stats.total_operations, 0);
        assert!(stats.last_operation_time.is_none());
    }

    #[test]
    fn test_embedded_power_protector_builder() {
        let protector = EmbeddedPowerProtectorBuilder::new()
            .cortex_m_optimization(true)
            .power_masking_strength(0.9)
            .random_delay_range(20, 80)
            .clock_jitter(true, 0.4)
            .power_noise(true, 0.6)
            .build();

        let stats = protector.stats();
        assert_eq!(stats.power_masking_strength, 0.9);
        assert!(stats.cortex_m_optimization_enabled);
    }

    #[test]
    fn test_protect_operation() {
        let protector = EmbeddedPowerProtector::new(EmbeddedPowerConfig::default());

        let result = protector.protect_operation(|| Ok::<_, CryptoError>(42));

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 42);

        let stats = protector.stats();
        assert_eq!(stats.total_operations, 1);
        assert!(stats.last_operation_time.is_some());
    }

    #[test]
    fn test_multiple_operations() {
        let protector = EmbeddedPowerProtector::new(EmbeddedPowerConfig::default());

        for i in 0..5 {
            let result = protector.protect_operation(|| Ok::<_, CryptoError>(i));
            assert!(result.is_ok());
            assert_eq!(result.unwrap(), i);
        }

        let stats = protector.stats();
        assert_eq!(stats.total_operations, 5);
    }
}