apple-cryptokit-rs 0.1.2

A Rust wrapper around Apple's native CryptoKit framework for App Store compliant cryptography.
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
//! # 密钥封装机制 (Key Encapsulation Mechanisms)
//!
//! 本模块实现了抗量子攻击的密钥封装机制,包括:
//! - ML-KEM768: 基于格的密钥封装机制,安全级别1
//! - ML-KEM1024: 基于格的密钥封装机制,安全级别3
//! - X-Wing: 混合KEM,结合了ML-KEM768和X25519
//!
//! 这些算法提供量子安全的密钥交换功能。

use crate::quantum::QuantumSafe;
use crate::{CryptoKitError, Result};

/// 密钥封装机制的通用特征
pub trait KeyEncapsulationMechanism: QuantumSafe {
    type PrivateKey: KEMPrivateKey;
    type PublicKey: KEMPublicKey;

    /// 生成新的私钥
    fn generate_private_key() -> Result<Self::PrivateKey>;
}

/// KEM私钥的通用特征
pub trait KEMPrivateKey {
    type PublicKey: KEMPublicKey;
    type SharedSecret;

    /// 获取对应的公钥
    fn public_key(&self) -> Self::PublicKey;

    /// 解封装密文,获得共享密钥
    fn decapsulate(&self, ciphertext: &[u8]) -> Result<Self::SharedSecret>;

    /// 将私钥序列化为字节数组
    fn to_bytes(&self) -> Vec<u8>;

    /// 从字节数组反序列化私钥
    fn from_bytes(bytes: &[u8]) -> Result<Self>
    where
        Self: Sized;
}

/// KEM公钥的通用特征
pub trait KEMPublicKey {
    type SharedSecret;

    /// 封装操作,生成密文和共享密钥
    fn encapsulate(&self) -> Result<(Vec<u8>, Self::SharedSecret)>;

    /// 将公钥序列化为字节数组
    fn to_bytes(&self) -> Vec<u8>;

    /// 从字节数组反序列化公钥
    fn from_bytes(bytes: &[u8]) -> Result<Self>
    where
        Self: Sized;
}

// ML-KEM768 实现

/// ML-KEM768 算法(安全级别1)
pub struct MLKem768;

impl QuantumSafe for MLKem768 {
    fn algorithm_name() -> &'static str {
        "ML-KEM-768"
    }

    fn security_level() -> u8 {
        1 // NIST 安全级别 1
    }
}

impl KeyEncapsulationMechanism for MLKem768 {
    type PrivateKey = MLKem768PrivateKey;
    type PublicKey = MLKem768PublicKey;

    fn generate_private_key() -> Result<Self::PrivateKey> {
        unsafe {
            let mut private_key_bytes = vec![0u8; MLKEM768_PRIVATE_KEY_SIZE];
            let mut public_key_bytes = vec![0u8; MLKEM768_PUBLIC_KEY_SIZE];

            let result = swift_mlkem768_generate_keypair(
                private_key_bytes.as_mut_ptr(),
                public_key_bytes.as_mut_ptr(),
            );

            if result != 0 {
                return Err(CryptoKitError::KeyGenerationFailed);
            }

            Ok(MLKem768PrivateKey {
                bytes: private_key_bytes,
                public_key: MLKem768PublicKey {
                    bytes: public_key_bytes,
                },
            })
        }
    }
}

/// ML-KEM768 私钥
pub struct MLKem768PrivateKey {
    bytes: Vec<u8>,
    public_key: MLKem768PublicKey,
}

impl KEMPrivateKey for MLKem768PrivateKey {
    type PublicKey = MLKem768PublicKey;
    type SharedSecret = [u8; 32];

    fn public_key(&self) -> Self::PublicKey {
        self.public_key.clone()
    }

    fn decapsulate(&self, ciphertext: &[u8]) -> Result<Self::SharedSecret> {
        if ciphertext.len() != MLKEM768_CIPHERTEXT_SIZE {
            return Err(CryptoKitError::InvalidInput(
                "Invalid ciphertext length".to_string(),
            ));
        }

        unsafe {
            let mut shared_secret = [0u8; 32];

            let result = swift_mlkem768_decapsulate(
                self.bytes.as_ptr(),
                ciphertext.as_ptr(),
                shared_secret.as_mut_ptr(),
            );

            if result != 0 {
                return Err(CryptoKitError::DecryptionFailed);
            }

            Ok(shared_secret)
        }
    }

    fn to_bytes(&self) -> Vec<u8> {
        self.bytes.clone()
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self> {
        if bytes.len() != MLKEM768_PRIVATE_KEY_SIZE {
            return Err(CryptoKitError::InvalidInput(
                "Invalid private key length".to_string(),
            ));
        }

        // 从私钥推导公钥
        unsafe {
            let mut public_key_bytes = vec![0u8; MLKEM768_PUBLIC_KEY_SIZE];

            let result =
                swift_mlkem768_derive_public_key(bytes.as_ptr(), public_key_bytes.as_mut_ptr());

            if result != 0 {
                return Err(CryptoKitError::InvalidInput(
                    "Invalid private key".to_string(),
                ));
            }

            Ok(MLKem768PrivateKey {
                bytes: bytes.to_vec(),
                public_key: MLKem768PublicKey {
                    bytes: public_key_bytes,
                },
            })
        }
    }
}

/// ML-KEM768 公钥
#[derive(Clone)]
pub struct MLKem768PublicKey {
    bytes: Vec<u8>,
}

impl KEMPublicKey for MLKem768PublicKey {
    type SharedSecret = [u8; 32];

    fn encapsulate(&self) -> Result<(Vec<u8>, Self::SharedSecret)> {
        unsafe {
            let mut ciphertext = vec![0u8; MLKEM768_CIPHERTEXT_SIZE];
            let mut shared_secret = [0u8; 32];

            let result = swift_mlkem768_encapsulate(
                self.bytes.as_ptr(),
                ciphertext.as_mut_ptr(),
                shared_secret.as_mut_ptr(),
            );

            if result != 0 {
                return Err(CryptoKitError::EncryptionFailed);
            }

            Ok((ciphertext, shared_secret))
        }
    }

    fn to_bytes(&self) -> Vec<u8> {
        self.bytes.clone()
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self> {
        if bytes.len() != MLKEM768_PUBLIC_KEY_SIZE {
            return Err(CryptoKitError::InvalidInput(
                "Invalid public key length".to_string(),
            ));
        }

        Ok(MLKem768PublicKey {
            bytes: bytes.to_vec(),
        })
    }
}

// ML-KEM1024 实现

/// ML-KEM1024 算法(安全级别3)
pub struct MLKem1024;

impl QuantumSafe for MLKem1024 {
    fn algorithm_name() -> &'static str {
        "ML-KEM-1024"
    }

    fn security_level() -> u8 {
        3 // NIST 安全级别 3
    }
}

impl KeyEncapsulationMechanism for MLKem1024 {
    type PrivateKey = MLKem1024PrivateKey;
    type PublicKey = MLKem1024PublicKey;

    fn generate_private_key() -> Result<Self::PrivateKey> {
        unsafe {
            let mut private_key_bytes = vec![0u8; MLKEM1024_PRIVATE_KEY_SIZE];
            let mut public_key_bytes = vec![0u8; MLKEM1024_PUBLIC_KEY_SIZE];

            let result = swift_mlkem1024_generate_keypair(
                private_key_bytes.as_mut_ptr(),
                public_key_bytes.as_mut_ptr(),
            );

            if result != 0 {
                return Err(CryptoKitError::KeyGenerationFailed);
            }

            Ok(MLKem1024PrivateKey {
                bytes: private_key_bytes,
                public_key: MLKem1024PublicKey {
                    bytes: public_key_bytes,
                },
            })
        }
    }
}

/// ML-KEM1024 私钥
pub struct MLKem1024PrivateKey {
    bytes: Vec<u8>,
    public_key: MLKem1024PublicKey,
}

impl KEMPrivateKey for MLKem1024PrivateKey {
    type PublicKey = MLKem1024PublicKey;
    type SharedSecret = [u8; 32];

    fn public_key(&self) -> Self::PublicKey {
        self.public_key.clone()
    }

    fn decapsulate(&self, ciphertext: &[u8]) -> Result<Self::SharedSecret> {
        if ciphertext.len() != MLKEM1024_CIPHERTEXT_SIZE {
            return Err(CryptoKitError::InvalidInput(
                "Invalid ciphertext length".to_string(),
            ));
        }

        unsafe {
            let mut shared_secret = [0u8; 32];

            let result = swift_mlkem1024_decapsulate(
                self.bytes.as_ptr(),
                ciphertext.as_ptr(),
                shared_secret.as_mut_ptr(),
            );

            if result != 0 {
                return Err(CryptoKitError::DecryptionFailed);
            }

            Ok(shared_secret)
        }
    }

    fn to_bytes(&self) -> Vec<u8> {
        self.bytes.clone()
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self> {
        if bytes.len() != MLKEM1024_PRIVATE_KEY_SIZE {
            return Err(CryptoKitError::InvalidInput(
                "Invalid private key length".to_string(),
            ));
        }

        // 从私钥推导公钥
        unsafe {
            let mut public_key_bytes = vec![0u8; MLKEM1024_PUBLIC_KEY_SIZE];

            let result =
                swift_mlkem1024_derive_public_key(bytes.as_ptr(), public_key_bytes.as_mut_ptr());

            if result != 0 {
                return Err(CryptoKitError::InvalidInput(
                    "Invalid private key".to_string(),
                ));
            }

            Ok(MLKem1024PrivateKey {
                bytes: bytes.to_vec(),
                public_key: MLKem1024PublicKey {
                    bytes: public_key_bytes,
                },
            })
        }
    }
}

/// ML-KEM1024 公钥
#[derive(Clone)]
pub struct MLKem1024PublicKey {
    bytes: Vec<u8>,
}

impl KEMPublicKey for MLKem1024PublicKey {
    type SharedSecret = [u8; 32];

    fn encapsulate(&self) -> Result<(Vec<u8>, Self::SharedSecret)> {
        unsafe {
            let mut ciphertext = vec![0u8; MLKEM1024_CIPHERTEXT_SIZE];
            let mut shared_secret = [0u8; 32];

            let result = swift_mlkem1024_encapsulate(
                self.bytes.as_ptr(),
                ciphertext.as_mut_ptr(),
                shared_secret.as_mut_ptr(),
            );

            if result != 0 {
                return Err(CryptoKitError::EncryptionFailed);
            }

            Ok((ciphertext, shared_secret))
        }
    }

    fn to_bytes(&self) -> Vec<u8> {
        self.bytes.clone()
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self> {
        if bytes.len() != MLKEM1024_PUBLIC_KEY_SIZE {
            return Err(CryptoKitError::InvalidInput(
                "Invalid public key length".to_string(),
            ));
        }

        Ok(MLKem1024PublicKey {
            bytes: bytes.to_vec(),
        })
    }
}

// X-Wing 混合KEM 实现

/// X-Wing (ML-KEM768 + X25519) 混合KEM
pub struct XWingMLKem768X25519;

impl QuantumSafe for XWingMLKem768X25519 {
    fn algorithm_name() -> &'static str {
        "X-Wing-ML-KEM768-X25519"
    }

    fn security_level() -> u8 {
        1 // 基于ML-KEM768的安全级别
    }
}

impl KeyEncapsulationMechanism for XWingMLKem768X25519 {
    type PrivateKey = XWingMLKem768X25519PrivateKey;
    type PublicKey = XWingMLKem768X25519PublicKey;

    fn generate_private_key() -> Result<Self::PrivateKey> {
        unsafe {
            let mut private_key_bytes = vec![0u8; XWING_PRIVATE_KEY_SIZE];
            let mut public_key_bytes = vec![0u8; XWING_PUBLIC_KEY_SIZE];

            let result = swift_xwing_generate_keypair(
                private_key_bytes.as_mut_ptr(),
                public_key_bytes.as_mut_ptr(),
            );

            if result != 0 {
                return Err(CryptoKitError::KeyGenerationFailed);
            }

            Ok(XWingMLKem768X25519PrivateKey {
                bytes: private_key_bytes,
                public_key: XWingMLKem768X25519PublicKey {
                    bytes: public_key_bytes,
                },
            })
        }
    }
}

/// X-Wing 私钥
pub struct XWingMLKem768X25519PrivateKey {
    bytes: Vec<u8>,
    public_key: XWingMLKem768X25519PublicKey,
}

impl KEMPrivateKey for XWingMLKem768X25519PrivateKey {
    type PublicKey = XWingMLKem768X25519PublicKey;
    type SharedSecret = [u8; 32];

    fn public_key(&self) -> Self::PublicKey {
        self.public_key.clone()
    }

    fn decapsulate(&self, ciphertext: &[u8]) -> Result<Self::SharedSecret> {
        if ciphertext.len() != XWING_CIPHERTEXT_SIZE {
            return Err(CryptoKitError::InvalidInput(
                "Invalid ciphertext length".to_string(),
            ));
        }

        unsafe {
            let mut shared_secret = [0u8; 32];

            let result = swift_xwing_decapsulate(
                self.bytes.as_ptr(),
                ciphertext.as_ptr(),
                shared_secret.as_mut_ptr(),
            );

            if result != 0 {
                return Err(CryptoKitError::DecryptionFailed);
            }

            Ok(shared_secret)
        }
    }

    fn to_bytes(&self) -> Vec<u8> {
        self.bytes.clone()
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self> {
        if bytes.len() != XWING_PRIVATE_KEY_SIZE {
            return Err(CryptoKitError::InvalidInput(
                "Invalid private key length".to_string(),
            ));
        }

        // 从私钥推导公钥
        unsafe {
            let mut public_key_bytes = vec![0u8; XWING_PUBLIC_KEY_SIZE];

            let result =
                swift_xwing_derive_public_key(bytes.as_ptr(), public_key_bytes.as_mut_ptr());

            if result != 0 {
                return Err(CryptoKitError::InvalidInput(
                    "Invalid private key".to_string(),
                ));
            }

            Ok(XWingMLKem768X25519PrivateKey {
                bytes: bytes.to_vec(),
                public_key: XWingMLKem768X25519PublicKey {
                    bytes: public_key_bytes,
                },
            })
        }
    }
}

/// X-Wing 公钥
#[derive(Clone)]
pub struct XWingMLKem768X25519PublicKey {
    bytes: Vec<u8>,
}

impl KEMPublicKey for XWingMLKem768X25519PublicKey {
    type SharedSecret = [u8; 32];

    fn encapsulate(&self) -> Result<(Vec<u8>, Self::SharedSecret)> {
        unsafe {
            let mut ciphertext = vec![0u8; XWING_CIPHERTEXT_SIZE];
            let mut shared_secret = [0u8; 32];

            let result = swift_xwing_encapsulate(
                self.bytes.as_ptr(),
                ciphertext.as_mut_ptr(),
                shared_secret.as_mut_ptr(),
            );

            if result != 0 {
                return Err(CryptoKitError::EncryptionFailed);
            }

            Ok((ciphertext, shared_secret))
        }
    }

    fn to_bytes(&self) -> Vec<u8> {
        self.bytes.clone()
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self> {
        if bytes.len() != XWING_PUBLIC_KEY_SIZE {
            return Err(CryptoKitError::InvalidInput(
                "Invalid public key length".to_string(),
            ));
        }

        Ok(XWingMLKem768X25519PublicKey {
            bytes: bytes.to_vec(),
        })
    }
}

// 常量定义 - 根据NIST标准
const MLKEM768_PUBLIC_KEY_SIZE: usize = 1184;
const MLKEM768_PRIVATE_KEY_SIZE: usize = 2400;
const MLKEM768_CIPHERTEXT_SIZE: usize = 1088;

const MLKEM1024_PUBLIC_KEY_SIZE: usize = 1568;
const MLKEM1024_PRIVATE_KEY_SIZE: usize = 3168;
const MLKEM1024_CIPHERTEXT_SIZE: usize = 1568;

const XWING_PUBLIC_KEY_SIZE: usize = 1216; // ML-KEM768 公钥 + X25519 公钥
const XWING_PRIVATE_KEY_SIZE: usize = 2432; // ML-KEM768 私钥 + X25519 私钥
const XWING_CIPHERTEXT_SIZE: usize = 1120; // ML-KEM768 密文 + X25519 密文

// Swift FFI 声明
extern "C" {
    // ML-KEM768
    fn swift_mlkem768_generate_keypair(private_key: *mut u8, public_key: *mut u8) -> i32;
    fn swift_mlkem768_encapsulate(
        public_key: *const u8,
        ciphertext: *mut u8,
        shared_secret: *mut u8,
    ) -> i32;
    fn swift_mlkem768_decapsulate(
        private_key: *const u8,
        ciphertext: *const u8,
        shared_secret: *mut u8,
    ) -> i32;
    fn swift_mlkem768_derive_public_key(private_key: *const u8, public_key: *mut u8) -> i32;

    // ML-KEM1024
    fn swift_mlkem1024_generate_keypair(private_key: *mut u8, public_key: *mut u8) -> i32;
    fn swift_mlkem1024_encapsulate(
        public_key: *const u8,
        ciphertext: *mut u8,
        shared_secret: *mut u8,
    ) -> i32;
    fn swift_mlkem1024_decapsulate(
        private_key: *const u8,
        ciphertext: *const u8,
        shared_secret: *mut u8,
    ) -> i32;
    fn swift_mlkem1024_derive_public_key(private_key: *const u8, public_key: *mut u8) -> i32;

    // X-Wing
    fn swift_xwing_generate_keypair(private_key: *mut u8, public_key: *mut u8) -> i32;
    fn swift_xwing_encapsulate(
        public_key: *const u8,
        ciphertext: *mut u8,
        shared_secret: *mut u8,
    ) -> i32;
    fn swift_xwing_decapsulate(
        private_key: *const u8,
        ciphertext: *const u8,
        shared_secret: *mut u8,
    ) -> i32;
    fn swift_xwing_derive_public_key(private_key: *const u8, public_key: *mut u8) -> i32;
}