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
use crate::{
    error::CryptoError,
    key_sources::{BytesKeySources, KeySources},
};
use serde::{Deserialize, Serialize};
use sodiumoxide::crypto::{
    box_::{
        self,
        curve25519xsalsa20poly1305::{PublicKey, SecretKey},
    },
    secretbox::{self, xsalsa20poly1305::Key as SoKey},
};
use std::convert::TryInto;

/// An encryptor that encrypts plaintexts with symmetric keys
pub trait SymmetricKeyEncryptor {
    fn try_encrypt(
        &self,
        key_source: &KeySources,
        plaintext: &[u8],
    ) -> Result<Vec<u8>, CryptoError>;
}

/// An encryptor that encrypts plaintexts with asymmetric keys
pub trait AsymmetricKeyEncryptor {
    fn try_encrypt(
        &self,
        key_source: &KeySources,
        public_ks: &KeySources,
        plaintext: &[u8],
    ) -> Result<Vec<u8>, CryptoError>;
}

/// Returned when requesting more than one `Key`. The collection
/// is represented as a vector of `Key` structs.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct KeyCollection {
    pub results: Vec<Key>,
}

/// The highest-level `Key` struct. This type can be serialized/deserialized
/// using serde for sharing across apps in a data storer. More importantly, future non-Byte
/// keys will be stored as mere references and can be loaded immediately and used when the
/// host laptop is connected to the matching hardware device.
///
/// The struct contains `KeyExecutors` and `KeySources` enums. These are the foundational
/// components. View their respective doumentation for further information.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Key {
    pub name: String,
    pub executor: KeyExecutors,
    pub source: KeySources,
    pub alg: String,
    pub encrypted_by: Option<String>,
}

impl Key {
    pub fn new(
        name: String,
        executor: KeyExecutors,
        source: KeySources,
        alg: String,
        encrypted_by: Option<String>,
    ) -> Result<Self, CryptoError> {
        Ok(Key {
            name,
            executor,
            source,
            alg,
            encrypted_by,
        })
    }

    pub fn name(&self) -> &str {
        &self.name
    }

    pub fn executor(&self) -> &KeyExecutors {
        &self.executor
    }

    pub fn source(&self) -> &KeySources {
        &self.source
    }

    pub fn encrypted_by(&self) -> &Option<String> {
        &self.encrypted_by
    }

    pub fn alg(&self) -> &str {
        &self.alg
    }
}

/// The `KeyExecutors` enum breaks down different types of executors based on whether the
/// executor operates on symmetric or asymmetric keys.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum KeyExecutors {
    Symmetric(SymmetricKeyExecutors),
    Asymmetric(AsymmetricKeyExecutors),
}

// impl KeyExecutors {
//     pub fn name(&self) -> &str {
//         match self {
//             Self::Symmetric(sk) => &sk.name(),
//             Self::Asymmetric(ak) => &ak.name(),
//         }
//     }

//     pub fn source(&self) -> &KeySources {
//         match self {
//             Self::Symmetric(sk) => &sk.source(),
//             Self::Asymmetric(ak) => &ak.source(),
//         }
//     }

//     pub fn encrypted_by(&self) -> &Option<String> {
//         match self {
//             Self::Symmetric(sk) => &sk.encrypted_by(),
//             Self::Asymmetric(ak) => &ak.encrypted_by(),
//         }
//     }

//     pub fn alg(&self) -> &str {
//         match self {
//             Self::Symmetric(sk) => &sk.alg(),
//             Self::Asymmetric(ak) => &ak.alg(),
//         }
//     }
// }

// impl TryFrom<KeyExecutors> for SymmetricKeyExecutors {
//     type Error = CryptoError;

//     fn try_from(key: KeyExecutors) -> Result<Self, Self::Error> {
//         match key {
//             KeyExecutors::Symmetric(sk) => Ok(sk),
//             _ => Err(CryptoError::NotSymmetric),
//         }
//     }
// }

// impl TryFrom<KeyExecutors> for AsymmetricKeyExecutors {
//     type Error = CryptoError;

//     fn try_from(key: KeyExecutors) -> Result<Self, Self::Error> {
//         match key {
//             KeyExecutors::Asymmetric(ak) => Ok(ak),
//             _ => Err(CryptoError::NotAsymmetric),
//         }
//     }
// }

// impl TryFrom<KeyExecutors> for SecretKeyExecutors {
//     type Error = CryptoError;

//     fn try_from(key: KeyExecutors) -> Result<Self, Self::Error> {
//         let asym_key: AsymmetricKeyExecutors = key.try_into()?;
//         asym_key.try_into()
//     }
// }

// impl TryFrom<KeyExecutors> for PublicKeyExecutors {
//     type Error = CryptoError;

//     fn try_from(key: KeyExecutors) -> Result<Self, Self::Error> {
//         let asym_key: AsymmetricKeyExecutors = key.try_into()?;
//         asym_key.try_into()
//     }
// }

/// This enum further breaks down symmetric keys into specifically implemented types.
/// Currently, the supported symmetric key executor types are:
/// SodiumOxide: symmetric key execution backed by libsodium's algorithms
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum SymmetricKeyExecutors {
    SodiumOxide(SodiumOxideSymmetricKeyExecutor),
}

// impl SymmetricKeyExecutors {
//     pub fn name(&self) -> &str {
//         match self {
//             Self::SodiumOxide(sosk) => &sosk.name(),
//         }
//     }

//     pub fn source(&self) -> &KeySources {
//         match self {
//             Self::SodiumOxide(sosk) => &sosk.source(),
//         }
//     }

//     pub fn encrypted_by(&self) -> &Option<String> {
//         match self {
//             Self::SodiumOxide(sosk) => &sosk.encrypted_by(),
//         }
//     }

//     pub fn alg(&self) -> &str {
//         match self {
//             Self::SodiumOxide(sosk) => &sosk.alg(),
//         }
//     }
// }

/// Implements symmetric key execution using libsodium's symmetric key algorithms
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct SodiumOxideSymmetricKeyExecutor {}

// impl SodiumOxideSymmetricKeyExecutor {
//     pub fn name(&self) -> &str {
//         &self.name
//     }

//     pub fn source(&self) -> &KeySources {
//         &self.source
//     }

//     pub fn encrypted_by(&self) -> &Option<String> {
//         &self.encrypted_by
//     }

//     pub fn alg(&self) -> &str {
//         &self.alg
//     }
// }

impl SymmetricKeyEncryptor for SodiumOxideSymmetricKeyExecutor {
    /// Encrypts the given plaintext using the given `KeySources`. If the source can not beo
    /// deserialized into a `BytesKeySources`, the function will return an `Err`.
    fn try_encrypt(
        &self,
        key_source: &KeySources,
        plaintext: &[u8],
    ) -> Result<Vec<u8>, CryptoError> {
        let key_source: BytesKeySources = key_source.clone().try_into()?;
        let key_bytes = key_source.get()?;
        let key: SoKey = SoKey::from_slice(key_bytes).ok_or(CryptoError::SourceKeyBadSize)?;
        let nonce = secretbox::gen_nonce();
        Ok(secretbox::seal(plaintext, &nonce, &key))
    }
}

/// This enum breaks down asymmetric key executors into public key operations
/// and secret key operations
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum AsymmetricKeyExecutors {
    Public(PublicKeyExecutors),
    Secret(SecretKeyExecutors),
}

// impl AsymmetricKeyExecutors {
//     pub fn name(&self) -> &str {
//         match self {
//             Self::Public(pk) => &pk.name(),
//             Self::Secret(sk) => &sk.name(),
//         }
//     }

//     pub fn source(&self) -> &KeySources {
//         match self {
//             Self::Public(pk) => &pk.source(),
//             Self::Secret(sk) => &sk.source(),
//         }
//     }

//     pub fn encrypted_by(&self) -> &Option<String> {
//         match self {
//             Self::Public(pk) => &pk.encrypted_by(),
//             Self::Secret(sk) => &sk.encrypted_by(),
//         }
//     }

//     pub fn alg(&self) -> &str {
//         match self {
//             Self::Public(pk) => &pk.alg(),
//             Self::Secret(sk) => &sk.alg(),
//         }
//     }
// }

/// This enum breaks down public key executors into specific implementations.
/// Current supported implementations are:
/// - SodiumOxide: public key logic backed by liboxide's public key algorithms
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum PublicKeyExecutors {
    SodiumOxide(SodiumOxidePublicKeyExecutor),
}

// impl PublicKeyExecutors {
//     pub fn name(&self) -> &str {
//         match self {
//             Self::SodiumOxide(sopk) => &sopk.name(),
//         }
//     }

//     pub fn source(&self) -> &KeySources {
//         match self {
//             Self::SodiumOxide(sopk) => &sopk.source(),
//         }
//     }

//     pub fn encrypted_by(&self) -> &Option<String> {
//         match self {
//             Self::SodiumOxide(sopk) => &sopk.encrypted_by(),
//         }
//     }

//     pub fn alg(&self) -> &str {
//         match self {
//             Self::SodiumOxide(sopk) => &sopk.alg(),
//         }
//     }
// }

/// This enum breaks down secret key executors into specific implementations.
/// Current supported implementations are:
/// - SodiumOxide: secret key logic backed by liboxide's secret key algorithms
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum SecretKeyExecutors {
    SodiumOxide(SodiumOxideSecretKeyExecutor),
}

// impl SecretKeyExecutors {
//     pub fn name(&self) -> &str {
//         match self {
//             Self::SodiumOxide(sosk) => &sosk.name(),
//         }
//     }

//     pub fn source(&self) -> &KeySources {
//         match self {
//             Self::SodiumOxide(sosk) => &sosk.source(),
//         }
//     }

//     pub fn encrypted_by(&self) -> &Option<String> {
//         match self {
//             Self::SodiumOxide(sosk) => &sosk.encrypted_by(),
//         }
//     }

//     pub fn alg(&self) -> &str {
//         match self {
//             Self::SodiumOxide(sosk) => &sosk.alg(),
//         }
//     }
// }

/// Implements public key execution logic using libsodium's algorithms
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct SodiumOxidePublicKeyExecutor {}

// impl SodiumOxidePublicKeyExecutor {
//     pub fn name(&self) -> &str {
//         &self.name
//     }

//     pub fn source(&self) -> &KeySources {
//         &self.source
//     }

//     pub fn encrypted_by(&self) -> &Option<String> {
//         &self.encrypted_by
//     }

//     pub fn alg(&self) -> &str {
//         &self.alg
//     }
// }

// impl TryFrom<AsymmetricKeyExecutors> for SecretKeyExecutors {
//     type Error = CryptoError;

//     fn try_from(ak: AsymmetricKeyExecutors) -> Result<Self, Self::Error> {
//         match ak {
//             AsymmetricKeyExecutors::Secret(sk) => Ok(sk),
//             _ => Err(CryptoError::NotSecret),
//         }
//     }
// }

// impl TryFrom<AsymmetricKeyExecutors> for PublicKeyExecutors {
//     type Error = CryptoError;

//     fn try_from(ak: AsymmetricKeyExecutors) -> Result<Self, Self::Error> {
//         match ak {
//             AsymmetricKeyExecutors::Secret(sk) => sk.try_into(),
//             AsymmetricKeyExecutors::Public(pk) => Ok(pk),
//         }
//     }
// }

// impl TryFrom<SecretKeyExecutors> for PublicKeyExecutors {
//     type Error = CryptoError;

//     fn try_from(sk: SecretKeyExecutors) -> Result<Self, Self::Error> {
//         match sk {
//             SecretKeyExecutors::SodiumOxide(sosk) => {
//                 let secret_key = SecretKey::from_slice(
//                     TryInto::<BytesKeySources>::try_into(sosk.source)?.get()?,
//                 )
//                 .ok_or(CryptoError::SourceKeyBadSize)?;
//                 let public_key = secret_key.public_key();
//                 let vbks = VectorBytesKeySource::new(Some(public_key.as_ref()));

//                 Ok(PublicKeyExecutors::SodiumOxide(
//                     SodiumOxidePublicKeyExecutor {
//                         source: KeySources::Bytes(BytesKeySources::Vector(vbks)),
//                         alg: "curve25519xsalsa20poly1305".to_owned(),
//                         encrypted_by: None,
//                         name: sosk.name,
//                     },
//                 ))
//             }
//         }
//     }
// }

/// Implements secret key execution logic using libsodium's algorithms
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct SodiumOxideSecretKeyExecutor {}

impl AsymmetricKeyEncryptor for SecretKeyExecutors {
    /// Passes through the call to the underlying encryptor variant
    fn try_encrypt(
        &self,
        key_source: &KeySources,
        public_ks: &KeySources,
        plaintext: &[u8],
    ) -> Result<Vec<u8>, CryptoError> {
        match self {
            SecretKeyExecutors::SodiumOxide(sosk) => {
                sosk.try_encrypt(key_source, public_ks, plaintext)
            }
        }
    }
}

// impl TryFrom<SodiumOxideSecretKeyExecutor> for SodiumOxidePublicKeyExecutor {
//     type Error = CryptoError;

//     fn try_from(sosk: SodiumOxideSecretKeyExecutor) -> Result<Self, Self::Error> {
//         let bks: BytesKeySources = sosk.source.try_into()?;
//         let secret_key_bytes = bks.get()?;

//         let secret_key =
//             SecretKey::from_slice(secret_key_bytes).ok_or(CryptoError::SourceKeyBadSize)?;
//         let public_key = secret_key.public_key();
//         Ok(SodiumOxidePublicKeyExecutor {
//             source: KeySources::Bytes(BytesKeySources::Vector(VectorBytesKeySource::new(Some(
//                 public_key.as_ref(),
//             )))),
//             alg: "curve25519xsalsa20poly1305".to_owned(),
//             encrypted_by: None,
//             name: sosk.name,
//         })
//     }
// }

impl SodiumOxideSecretKeyExecutor {
    // pub fn name(&self) -> &str {
    //     &self.name
    // }

    // pub fn source(&self) -> &KeySources {
    //     &self.source
    // }

    // pub fn encrypted_by(&self) -> &Option<String> {
    //     &self.encrypted_by
    // }

    // pub fn alg(&self) -> &str {
    //     &self.alg
    // }

    // pub fn new(
    //     name: &str,
    //     source: KeySources,
    //     alg: &str,
    //     encrypted_by: Option<String>,
    // ) -> Result<Self, CryptoError> {
    //     let mut bks: BytesKeySources = source.try_into()?;
    //     match bks.get() {
    //         Ok(_) => Ok(SodiumOxideSecretKeyExecutor {
    //             name: name.to_owned(),
    //             source: KeySources::Bytes(bks),
    //             alg: alg.to_owned(),
    //             encrypted_by,
    //         }),
    //         Err(e) => match e {
    //             CryptoError::NotFound => {
    //                 let (_, sk) = box_::gen_keypair();
    //                 bks.set(sk.as_ref())?;
    //                 Ok(SodiumOxideSecretKeyExecutor {
    //                     name: name.to_owned(),
    //                     source: KeySources::Bytes(bks),
    //                     alg: alg.to_owned(),
    //                     encrypted_by,
    //                 })
    //             }
    //             _ => Err(e),
    //         },
    //     }
    // }
}

impl AsymmetricKeyEncryptor for SodiumOxideSecretKeyExecutor {
    /// Encrypts the given plaintext using the given `KeySources`. If the source can not be
    /// deserialized into a `BytesKeySources`, the function will return an `Err`.
    fn try_encrypt(
        &self,
        key_source: &KeySources,
        public_ks: &KeySources,
        plaintext: &[u8],
    ) -> Result<Vec<u8>, CryptoError> {
        let secret_bks: BytesKeySources = key_source.clone().try_into()?;
        let public_bks: BytesKeySources = public_ks.clone().try_into()?;
        let secret_key_bytes = secret_bks.get()?;
        let public_key_bytes = public_bks.get()?;
        let secret_key =
            SecretKey::from_slice(secret_key_bytes).ok_or(CryptoError::SourceKeyBadSize)?;
        let public_key =
            PublicKey::from_slice(public_key_bytes).ok_or(CryptoError::SourceKeyBadSize)?;
        let precomputed_key = box_::precompute(&public_key, &secret_key);
        let nonce = box_::gen_nonce();
        Ok(box_::seal_precomputed(&plaintext, &nonce, &precomputed_key))
    }
}

// impl<'de> DeserializeTrait<'de> for SodiumOxideSecretKeyExecutor {
//     fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
//     where
//         D: Deserializer<'de>,
//     {
//         enum Field {
//             Source,
//             Alg,
//             EncryptedBy,
//             Name,
//         }

//         impl<'de> Deserialize<'de> for Field {
//             fn deserialize<D>(deserializer: D) -> Result<Field, D::Error>
//             where
//                 D: Deserializer<'de>,
//             {
//                 struct FieldVisitor;

//                 impl<'de> Visitor<'de> for FieldVisitor {
//                     type Value = Field;

//                     fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
//                         formatter.write_str("`source` or `alg` or `encrypted_by` or `name`")
//                     }

//                     fn visit_str<E>(self, value: &str) -> Result<Field, E>
//                     where
//                         E: de::Error,
//                     {
//                         match value {
//                             "source" => Ok(Field::Source),
//                             "alg" => Ok(Field::Alg),
//                             "encrypted_by" => Ok(Field::EncryptedBy),
//                             "name" => Ok(Field::Name),
//                             _ => Err(de::Error::unknown_field(value, FIELDS)),
//                         }
//                     }
//                 }

//                 deserializer.deserialize_identifier(FieldVisitor)
//             }
//         }

//         struct SodiumOxideSecretKeyVisitor;

//         impl<'de> Visitor<'de> for SodiumOxideSecretKeyVisitor {
//             type Value = SodiumOxideSecretKeyExecutor;

//             fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
//                 formatter.write_str("struct SodiumOxideSecretKey")
//             }

//             fn visit_seq<V>(self, mut seq: V) -> Result<Self::Value, V::Error>
//             where
//                 V: SeqAccess<'de>,
//             {
//                 let source: KeySources = seq
//                     .next_element()?
//                     .ok_or_else(|| de::Error::invalid_length(0, &self))?;
//                 let alg = seq
//                     .next_element()?
//                     .ok_or_else(|| de::Error::invalid_length(0, &self))?;
//                 let encrypted_by = seq
//                     .next_element()?
//                     .ok_or_else(|| de::Error::invalid_length(0, &self))?;
//                 let name = seq
//                     .next_element()?
//                     .ok_or_else(|| de::Error::invalid_length(0, &self))?;

//                 SodiumOxideSecretKeyExecutor::new(name, source, alg, encrypted_by)
//                     .map_err(de::Error::custom)
//             }

//             fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
//             where
//                 V: MapAccess<'de>,
//             {
//                 let mut source = None;
//                 let mut name: Option<String> = None;
//                 let mut alg: Option<String> = None;
//                 let mut encrypted_by: Option<String> = None;

//                 while let Some(key) = map.next_key()? {
//                     match key {
//                         Field::Source => {
//                             if source.is_some() {
//                                 return Err(de::Error::duplicate_field("source"));
//                             }
//                             source = Some(map.next_value()?);
//                         }
//                         Field::Alg => {
//                             if alg.is_some() {
//                                 return Err(de::Error::duplicate_field("alg"));
//                             }
//                             alg = Some(map.next_value()?);
//                         }
//                         Field::EncryptedBy => {
//                             if encrypted_by.is_some() {
//                                 return Err(de::Error::duplicate_field("encrypted_by"));
//                             }
//                             let next_result = map.next_value();
//                             encrypted_by = Some(next_result?);
//                         }
//                         Field::Name => {
//                             if name.is_some() {
//                                 return Err(de::Error::duplicate_field("name"));
//                             }
//                             name = Some(map.next_value()?);
//                         }
//                     }
//                 }
//                 let source = source.ok_or_else(|| de::Error::missing_field("source"))?;
//                 let alg = alg.ok_or_else(|| de::Error::missing_field("alg"))?;
//                 let name = name.ok_or_else(|| de::Error::missing_field("name"))?;
//                 SodiumOxideSecretKeyExecutor::new(&name, source, &alg, encrypted_by)
//                     .map_err(de::Error::custom)
//             }
//         }

//         const FIELDS: &'static [&'static str] = &["source", "alg", "encrypted_by", "name"];
//         deserializer.deserialize_struct("SodiumOxideSecretKey", FIELDS, SodiumOxideSecretKeyVisitor)
//     }
// }