dcrypt-algorithms 1.2.3

Cryptographic primitives for the dcrypt 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
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
//! Type-safe key implementations with algorithm binding
//!
//! Provides key types with compile-time guarantees about their
//! usage and appropriate security properties.

use core::fmt;
use core::marker::PhantomData;
use core::ops::{Deref, DerefMut};
use rand::{CryptoRng, RngCore};
use subtle::ConstantTimeEq;
use zeroize::{Zeroize, ZeroizeOnDrop};

use crate::error::{validate, Result};
use crate::types::sealed::Sealed;
use crate::types::{
    ByteSerializable, ConstantTimeEq as LocalConstantEq, FixedSize, RandomGeneration,
    SecureZeroingType,
};
use crate::types::{ValidKeySize, ValidPublicKeySize, ValidSecretKeySize};

// Import security types from dcrypt-core
use dcrypt_common::security::SecretBuffer;

// Add these imports to fix the "cannot find type" errors
use crate::types::algorithms::{
    Aes128, Aes256, ChaCha20, ChaCha20Poly1305, Ed25519, P256, P384, P521, X25519,
};

/// Marker trait for symmetric algorithms
pub trait SymmetricAlgorithm {
    /// Key size in bytes
    const KEY_SIZE: usize;

    /// Block size in bytes (if applicable)
    const BLOCK_SIZE: usize;

    /// Algorithm identifier
    const ALGORITHM_ID: &'static str;

    /// Algorithm name
    fn name() -> String {
        Self::ALGORITHM_ID.to_string()
    }
}

/// Marker trait for asymmetric algorithms
pub trait AsymmetricAlgorithm {
    /// Public key size in bytes
    const PUBLIC_KEY_SIZE: usize;

    /// Secret key size in bytes
    const SECRET_KEY_SIZE: usize;

    /// Algorithm identifier
    const ALGORITHM_ID: &'static str;

    /// Algorithm name
    fn name() -> String {
        Self::ALGORITHM_ID.to_string()
    }
}

/// A key for a specific symmetric algorithm with fixed size
#[derive(Clone, Zeroize, ZeroizeOnDrop)]
pub struct SymmetricKey<A: SymmetricAlgorithm, const N: usize> {
    data: SecretBuffer<N>,
    _algorithm: PhantomData<A>,
}

// Mark types as sealed to prevent external implementations
impl<A: SymmetricAlgorithm, const N: usize> Sealed for SymmetricKey<A, N> {}

// Individual implementations for specific algorithm and size combinations
impl ValidKeySize<Aes128, 16> for SymmetricKey<Aes128, 16> {}
impl ValidKeySize<Aes256, 32> for SymmetricKey<Aes256, 32> {}
impl ValidKeySize<ChaCha20, 32> for SymmetricKey<ChaCha20, 32> {}
impl ValidKeySize<ChaCha20Poly1305, 32> for SymmetricKey<ChaCha20Poly1305, 32> {}

impl<A: SymmetricAlgorithm, const N: usize> SymmetricKey<A, N>
where
    Self: ValidKeySize<A, N>,
{
    /// Create a new key from an existing array
    pub fn new(data: [u8; N]) -> Self {
        Self {
            data: SecretBuffer::new(data),
            _algorithm: PhantomData,
        }
    }

    /// Create from a slice, if it has the correct length
    pub fn try_from_slice(bytes: &[u8]) -> Result<Self> {
        validate::length("SymmetricKey::from_slice", bytes.len(), N)?;

        let mut data = [0u8; N];
        data.copy_from_slice(bytes);

        Ok(Self {
            data: SecretBuffer::new(data),
            _algorithm: PhantomData,
        })
    }

    /// Create a zeroed key (not recommended for cryptographic use)
    pub fn zeroed() -> Self {
        Self {
            data: SecretBuffer::zeroed(),
            _algorithm: PhantomData,
        }
    }

    /// Get the algorithm name
    pub fn algorithm_name() -> String {
        A::name()
    }

    /// Get the key size in bytes
    pub fn key_size() -> usize {
        N
    }
}

impl<A: SymmetricAlgorithm, const N: usize> AsRef<[u8]> for SymmetricKey<A, N> {
    fn as_ref(&self) -> &[u8] {
        self.data.as_ref()
    }
}

impl<A: SymmetricAlgorithm, const N: usize> AsMut<[u8]> for SymmetricKey<A, N> {
    fn as_mut(&mut self) -> &mut [u8] {
        self.data.as_mut()
    }
}

impl<A: SymmetricAlgorithm, const N: usize> Deref for SymmetricKey<A, N> {
    type Target = [u8];

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

impl<A: SymmetricAlgorithm, const N: usize> DerefMut for SymmetricKey<A, N> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.data.as_mut()
    }
}

impl<A: SymmetricAlgorithm, const N: usize> PartialEq for SymmetricKey<A, N> {
    fn eq(&self, other: &Self) -> bool {
        // Use the subtle crate's ConstantTimeEq trait directly
        self.data.as_ref().ct_eq(other.data.as_ref()).into()
    }
}

impl<A: SymmetricAlgorithm, const N: usize> Eq for SymmetricKey<A, N> {}

impl<A: SymmetricAlgorithm, const N: usize> fmt::Debug for SymmetricKey<A, N> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "SymmetricKey<{}>[REDACTED]", A::name())
    }
}

impl<A: SymmetricAlgorithm, const N: usize> LocalConstantEq for SymmetricKey<A, N> {
    fn ct_eq(&self, other: &Self) -> bool {
        // Use the ConstantTimeEq trait from subtle for the inner data
        self.data.as_ref().ct_eq(other.data.as_ref()).into()
    }
}

impl<A: SymmetricAlgorithm, const N: usize> RandomGeneration for SymmetricKey<A, N> {
    fn random<R: RngCore + CryptoRng>(rng: &mut R) -> Result<Self> {
        let mut data = [0u8; N];
        rng.fill_bytes(&mut data);
        Ok(Self {
            data: SecretBuffer::new(data),
            _algorithm: PhantomData,
        })
    }
}

impl<A: SymmetricAlgorithm + Clone, const N: usize> SecureZeroingType for SymmetricKey<A, N> {
    fn zeroed() -> Self {
        Self {
            data: SecretBuffer::zeroed(),
            _algorithm: PhantomData,
        }
    }

    fn secure_clone(&self) -> Self {
        Self {
            data: self.data.secure_clone(),
            _algorithm: PhantomData,
        }
    }
}

impl<A: SymmetricAlgorithm, const N: usize> FixedSize for SymmetricKey<A, N> {
    fn size() -> usize {
        N
    }
}

// Implement ByteSerializable only for specific valid combinations
impl ByteSerializable for SymmetricKey<Aes128, 16> {
    fn to_bytes(&self) -> Vec<u8> {
        self.data.as_ref().to_vec()
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self> {
        Self::try_from_slice(bytes)
    }
}

impl ByteSerializable for SymmetricKey<Aes256, 32> {
    fn to_bytes(&self) -> Vec<u8> {
        self.data.as_ref().to_vec()
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self> {
        Self::try_from_slice(bytes)
    }
}

impl ByteSerializable for SymmetricKey<ChaCha20, 32> {
    fn to_bytes(&self) -> Vec<u8> {
        self.data.as_ref().to_vec()
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self> {
        Self::try_from_slice(bytes)
    }
}

impl ByteSerializable for SymmetricKey<ChaCha20Poly1305, 32> {
    fn to_bytes(&self) -> Vec<u8> {
        self.data.as_ref().to_vec()
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self> {
        Self::try_from_slice(bytes)
    }
}

/// A secret key for a specific asymmetric algorithm
#[derive(Clone, Zeroize, ZeroizeOnDrop)]
pub struct AsymmetricSecretKey<A: AsymmetricAlgorithm, const N: usize> {
    data: SecretBuffer<N>,
    _algorithm: PhantomData<A>,
}

// Mark types as sealed to prevent external implementations
impl<A: AsymmetricAlgorithm, const N: usize> Sealed for AsymmetricSecretKey<A, N> {}

// Individual implementations for specific algorithm and size combinations
impl ValidSecretKeySize<Ed25519, 32> for AsymmetricSecretKey<Ed25519, 32> {}
impl ValidSecretKeySize<X25519, 32> for AsymmetricSecretKey<X25519, 32> {}
impl ValidSecretKeySize<P256, 32> for AsymmetricSecretKey<P256, 32> {} // Added for P-256
impl ValidSecretKeySize<P384, 48> for AsymmetricSecretKey<P384, 48> {} // Added for P-384
impl ValidSecretKeySize<P521, 66> for AsymmetricSecretKey<P521, 66> {} // P-521

impl<A: AsymmetricAlgorithm, const N: usize> AsymmetricSecretKey<A, N>
where
    Self: ValidSecretKeySize<A, N>,
{
    /// Create a new key from an existing array
    pub fn new(data: [u8; N]) -> Self {
        Self {
            data: SecretBuffer::new(data),
            _algorithm: PhantomData,
        }
    }

    /// Create from a slice, if it has the correct length
    pub fn try_from_slice(bytes: &[u8]) -> Result<Self> {
        validate::length("AsymmetricSecretKey::from_slice", bytes.len(), N)?;

        let mut data = [0u8; N];
        data.copy_from_slice(bytes);

        Ok(Self {
            data: SecretBuffer::new(data),
            _algorithm: PhantomData,
        })
    }

    /// Create a zeroed key (not recommended for cryptographic use)
    pub fn zeroed() -> Self {
        Self {
            data: SecretBuffer::zeroed(),
            _algorithm: PhantomData,
        }
    }

    /// Get the algorithm name
    pub fn algorithm_name() -> String {
        A::name()
    }

    /// Get the key size in bytes
    pub fn key_size() -> usize {
        N
    }
}

impl<A: AsymmetricAlgorithm, const N: usize> AsRef<[u8]> for AsymmetricSecretKey<A, N> {
    fn as_ref(&self) -> &[u8] {
        self.data.as_ref()
    }
}

impl<A: AsymmetricAlgorithm, const N: usize> AsMut<[u8]> for AsymmetricSecretKey<A, N> {
    fn as_mut(&mut self) -> &mut [u8] {
        self.data.as_mut()
    }
}

impl<A: AsymmetricAlgorithm, const N: usize> Deref for AsymmetricSecretKey<A, N> {
    type Target = [u8];

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

impl<A: AsymmetricAlgorithm, const N: usize> DerefMut for AsymmetricSecretKey<A, N> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.data.as_mut()
    }
}

impl<A: AsymmetricAlgorithm, const N: usize> PartialEq for AsymmetricSecretKey<A, N> {
    fn eq(&self, other: &Self) -> bool {
        // Use constant-time comparison for secret keys
        self.data.as_ref().ct_eq(other.data.as_ref()).into()
    }
}

impl<A: AsymmetricAlgorithm, const N: usize> Eq for AsymmetricSecretKey<A, N> {}

impl<A: AsymmetricAlgorithm, const N: usize> fmt::Debug for AsymmetricSecretKey<A, N> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "AsymmetricSecretKey<{}>[REDACTED]", A::name())
    }
}

impl<A: AsymmetricAlgorithm + Clone, const N: usize> SecureZeroingType
    for AsymmetricSecretKey<A, N>
{
    fn zeroed() -> Self {
        Self {
            data: SecretBuffer::zeroed(),
            _algorithm: PhantomData,
        }
    }

    fn secure_clone(&self) -> Self {
        Self {
            data: self.data.secure_clone(),
            _algorithm: PhantomData,
        }
    }
}

impl<A: AsymmetricAlgorithm, const N: usize> FixedSize for AsymmetricSecretKey<A, N> {
    fn size() -> usize {
        N
    }
}

// Implement ByteSerializable only for specific valid combinations
impl ByteSerializable for AsymmetricSecretKey<Ed25519, 32> {
    fn to_bytes(&self) -> Vec<u8> {
        self.data.as_ref().to_vec()
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self> {
        Self::try_from_slice(bytes)
    }
}

impl ByteSerializable for AsymmetricSecretKey<X25519, 32> {
    fn to_bytes(&self) -> Vec<u8> {
        self.data.as_ref().to_vec()
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self> {
        Self::try_from_slice(bytes)
    }
}

impl ByteSerializable for AsymmetricSecretKey<P256, 32> {
    // Added for P-256
    fn to_bytes(&self) -> Vec<u8> {
        self.data.as_ref().to_vec()
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self> {
        Self::try_from_slice(bytes)
    }
}

impl ByteSerializable for AsymmetricSecretKey<P384, 48> {
    // Added for P-384
    fn to_bytes(&self) -> Vec<u8> {
        self.data.as_ref().to_vec()
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self> {
        Self::try_from_slice(bytes)
    }
}

impl ByteSerializable for AsymmetricSecretKey<P521, 66> {
    // P-521
    fn to_bytes(&self) -> Vec<u8> {
        self.data.as_ref().to_vec()
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self> {
        Self::try_from_slice(bytes)
    }
}

/// A public key for a specific asymmetric algorithm
///
/// Note: Public keys don't need SecretBuffer since they're not secret
#[derive(Clone)]
pub struct AsymmetricPublicKey<A: AsymmetricAlgorithm, const N: usize> {
    data: [u8; N],
    _algorithm: PhantomData<A>,
}

// Mark types as sealed to prevent external implementations
impl<A: AsymmetricAlgorithm, const N: usize> Sealed for AsymmetricPublicKey<A, N> {}

// Individual implementations for specific algorithm and size combinations
impl ValidPublicKeySize<Ed25519, 32> for AsymmetricPublicKey<Ed25519, 32> {}
impl ValidPublicKeySize<X25519, 32> for AsymmetricPublicKey<X25519, 32> {}
impl ValidPublicKeySize<P256, 65> for AsymmetricPublicKey<P256, 65> {} // Added for P-256 (uncompressed)
impl ValidPublicKeySize<P256, 33> for AsymmetricPublicKey<P256, 33> {} // Added for P-256 (compressed)
impl ValidPublicKeySize<P384, 97> for AsymmetricPublicKey<P384, 97> {} // Added for P-384 (uncompressed)
impl ValidPublicKeySize<P384, 49> for AsymmetricPublicKey<P384, 49> {} // Added for P-384 (compressed)
impl ValidPublicKeySize<P521, 133> for AsymmetricPublicKey<P521, 133> {} // P-521 (uncompressed)
impl ValidPublicKeySize<P521, 67> for AsymmetricPublicKey<P521, 67> {} // Added for P-521 (compressed)

impl<A: AsymmetricAlgorithm, const N: usize> AsymmetricPublicKey<A, N>
where
    Self: ValidPublicKeySize<A, N>,
{
    /// Create a new key from an existing array
    pub fn new(data: [u8; N]) -> Self {
        Self {
            data,
            _algorithm: PhantomData,
        }
    }

    /// Create from a slice, if it has the correct length
    pub fn try_from_slice(bytes: &[u8]) -> Result<Self> {
        validate::length("AsymmetricPublicKey::from_slice", bytes.len(), N)?;

        let mut data = [0u8; N];
        data.copy_from_slice(bytes);

        Ok(Self {
            data,
            _algorithm: PhantomData,
        })
    }

    /// Get the algorithm name
    pub fn algorithm_name() -> String {
        A::name()
    }

    /// Get the key size in bytes
    pub fn key_size() -> usize {
        N
    }
}

impl<A: AsymmetricAlgorithm, const N: usize> AsRef<[u8]> for AsymmetricPublicKey<A, N> {
    fn as_ref(&self) -> &[u8] {
        &self.data
    }
}

impl<A: AsymmetricAlgorithm, const N: usize> AsMut<[u8]> for AsymmetricPublicKey<A, N> {
    fn as_mut(&mut self) -> &mut [u8] {
        &mut self.data
    }
}

impl<A: AsymmetricAlgorithm, const N: usize> fmt::Debug for AsymmetricPublicKey<A, N> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "AsymmetricPublicKey<{}>({:?})",
            A::name(),
            &self.data[..]
        )
    }
}

impl<A: AsymmetricAlgorithm, const N: usize> PartialEq for AsymmetricPublicKey<A, N> {
    fn eq(&self, other: &Self) -> bool {
        self.data == other.data // Public keys can use direct comparison
    }
}

impl<A: AsymmetricAlgorithm, const N: usize> Eq for AsymmetricPublicKey<A, N> {}

impl<A: AsymmetricAlgorithm, const N: usize> FixedSize for AsymmetricPublicKey<A, N> {
    fn size() -> usize {
        N
    }
}

// Implement ByteSerializable only for specific valid combinations
impl ByteSerializable for AsymmetricPublicKey<Ed25519, 32> {
    fn to_bytes(&self) -> Vec<u8> {
        self.data.to_vec()
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self> {
        Self::try_from_slice(bytes)
    }
}

impl ByteSerializable for AsymmetricPublicKey<X25519, 32> {
    fn to_bytes(&self) -> Vec<u8> {
        self.data.to_vec()
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self> {
        Self::try_from_slice(bytes)
    }
}

impl ByteSerializable for AsymmetricPublicKey<P256, 65> {
    // Added for P-256 uncompressed
    fn to_bytes(&self) -> Vec<u8> {
        self.data.to_vec()
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self> {
        Self::try_from_slice(bytes)
    }
}

impl ByteSerializable for AsymmetricPublicKey<P256, 33> {
    // Added for P-256 compressed
    fn to_bytes(&self) -> Vec<u8> {
        self.data.to_vec()
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self> {
        Self::try_from_slice(bytes)
    }
}

impl ByteSerializable for AsymmetricPublicKey<P384, 97> {
    // Added for P-384 uncompressed
    fn to_bytes(&self) -> Vec<u8> {
        self.data.to_vec()
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self> {
        Self::try_from_slice(bytes)
    }
}

impl ByteSerializable for AsymmetricPublicKey<P384, 49> {
    // Added for P-384 compressed
    fn to_bytes(&self) -> Vec<u8> {
        self.data.to_vec()
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self> {
        Self::try_from_slice(bytes)
    }
}

impl ByteSerializable for AsymmetricPublicKey<P521, 133> {
    // P-521 uncompressed
    fn to_bytes(&self) -> Vec<u8> {
        self.data.to_vec()
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self> {
        Self::try_from_slice(bytes)
    }
}

impl ByteSerializable for AsymmetricPublicKey<P521, 67> {
    // Added for P-521 compressed
    fn to_bytes(&self) -> Vec<u8> {
        self.data.to_vec()
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self> {
        Self::try_from_slice(bytes)
    }
}