crypto-seal 0.2.5

A small utility designed to securely "package" or seal serde-compatible data type that can passed around in an uncompromised manner.
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
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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
use crate::{error::Error, Result};
use aes_gcm::{
    aead::stream::{DecryptorBE32, EncryptorBE32},
    aead::Aead,
    Aes256Gcm, Key, KeyInit, Nonce,
};
use core::hash::Hash;
use curve25519_dalek::edwards::CompressedEdwardsY;
use ed25519_dalek::{Digest, Sha512, Signature, Signer, Verifier};
use rand::rngs::OsRng;
use serde::{Deserialize, Deserializer, Serialize};
use std::io;
use zeroize::Zeroize;

/// Container of private keys
/// The following is supported
/// - [`ed25519_dalek`]
/// - [`secp256k1`]
/// - [`aes_gcm::Aes256Gcm`]
#[derive(Debug)]
pub enum PrivateKey {
    Ed25519(ed25519_dalek::Keypair),
    Secp256k1(secp256k1::SecretKey),
    Aes256([u8; 32]),
}

impl Default for PrivateKey {
    fn default() -> Self {
        Self::new_with(PrivateKeyType::default())
    }
}

impl Zeroize for PrivateKey {
    fn zeroize(&mut self) {
        match self {
            PrivateKey::Ed25519(kp) => {
                kp.secret.zeroize();
            }
            PrivateKey::Secp256k1(_kp) => {
                //TODO: Zeroize or destroy key
            }
            PrivateKey::Aes256(key) => {
                key.zeroize();
            }
        }
    }
}

impl Drop for PrivateKey {
    fn drop(&mut self) {
        self.zeroize()
    }
}

/// Container of public keys
/// The following is supported
/// - [`ed25519_dalek::PublicKey`]
#[derive(Debug, Clone, Eq)]
pub enum PublicKey {
    Ed25519(ed25519_dalek::PublicKey),
    Secp256k1(secp256k1::PublicKey),
}

impl core::fmt::Display for PublicKey {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", bs58::encode(self.encode()).into_string())
    }
}

impl Hash for PublicKey {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.encode().hash(state)
    }
}

impl PartialEq for PublicKey {
    fn eq(&self, other: &Self) -> bool {
        self.encode() == other.encode()
    }
}

impl Serialize for PublicKey {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let pk_str = bs58::encode(self.encode()).into_string();
        serializer.serialize_str(&pk_str)
    }
}

impl<'d> Deserialize<'d> for PublicKey {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'d>,
    {
        let pk_str = <String>::deserialize(deserializer)?;
        let bytes = bs58::decode(pk_str)
            .into_vec()
            .map_err(serde::de::Error::custom)?;
        PublicKey::decode(&bytes).map_err(serde::de::Error::custom)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum PublicKeyType {
    /// Ed25519 Public Key
    Ed25519,

    /// Secp256k1 Public Key
    Secp256k1,
}

impl TryFrom<u8> for PublicKeyType {
    type Error = Error;
    fn try_from(value: u8) -> std::result::Result<Self, Self::Error> {
        match value {
            0xa1 => Ok(PublicKeyType::Ed25519),
            0xb1 => Ok(PublicKeyType::Secp256k1),
            _ => Err(Error::InvalidPublickey),
        }
    }
}

impl From<PublicKeyType> for u8 {
    fn from(value: PublicKeyType) -> Self {
        match value {
            PublicKeyType::Ed25519 => 0xa1,
            PublicKeyType::Secp256k1 => 0xb1,
        }
    }
}

impl From<ed25519_dalek::PublicKey> for PublicKey {
    fn from(pk: ed25519_dalek::PublicKey) -> Self {
        PublicKey::Ed25519(pk)
    }
}

impl From<secp256k1::PublicKey> for PublicKey {
    fn from(pk: secp256k1::PublicKey) -> Self {
        PublicKey::Secp256k1(pk)
    }
}

impl TryFrom<PublicKey> for secp256k1::PublicKey {
    type Error = Error;

    fn try_from(value: PublicKey) -> std::result::Result<Self, Self::Error> {
        match value {
            PublicKey::Secp256k1(pk) => Ok(pk),
            PublicKey::Ed25519(_) => Err(Error::InvalidPublickey),
        }
    }
}

impl TryFrom<&PrivateKey> for x25519_dalek::StaticSecret {
    type Error = Error;

    fn try_from(value: &PrivateKey) -> std::result::Result<Self, Self::Error> {
        match value {
            PrivateKey::Ed25519(kp) => {
                let mut hasher: Sha512 = Sha512::new();
                hasher.update(kp.secret.as_ref());
                let hash = hasher.finalize().to_vec();
                let mut new_sk: [u8; 32] = [0; 32];
                new_sk.copy_from_slice(&hash[..32]);
                let sk = x25519_dalek::StaticSecret::from(new_sk);
                new_sk.zeroize();
                Ok(sk)
            }
            _ => Err(Error::Unsupported),
        }
    }
}

impl TryFrom<PrivateKey> for x25519_dalek::StaticSecret {
    type Error = Error;

    fn try_from(value: PrivateKey) -> std::result::Result<Self, Self::Error> {
        TryFrom::try_from(&value)
    }
}

impl TryFrom<PublicKey> for ed25519_dalek::PublicKey {
    type Error = Error;

    fn try_from(value: PublicKey) -> std::result::Result<Self, Self::Error> {
        match value {
            PublicKey::Secp256k1(_) => Err(Error::InvalidPublickey),
            PublicKey::Ed25519(pk) => Ok(pk),
        }
    }
}

impl TryFrom<PublicKey> for x25519_dalek::PublicKey {
    type Error = Error;

    fn try_from(value: PublicKey) -> std::result::Result<Self, Self::Error> {
        match value {
            PublicKey::Secp256k1(_) => Err(Error::InvalidPublickey),
            PublicKey::Ed25519(pk) => {
                let ep = CompressedEdwardsY(pk.to_bytes())
                    .decompress()
                    .ok_or(Error::Unsupported)?; //Note: This should not error here
                let mon = ep.to_montgomery();
                Ok(x25519_dalek::PublicKey::from(mon.0))
            }
        }
    }
}

impl PublicKey {
    pub fn from_bytes(key_type: PublicKeyType, bytes: &[u8]) -> Result<PublicKey> {
        match key_type {
            PublicKeyType::Ed25519 => Self::from_ed25519_bytes(bytes),
            PublicKeyType::Secp256k1 => Self::from_secp256k1_bytes(bytes),
        }
    }

    pub fn from_ed25519_bytes(bytes: &[u8]) -> Result<PublicKey> {
        let pk = ed25519_dalek::PublicKey::from_bytes(bytes)?;
        Ok(PublicKey::Ed25519(pk))
    }

    pub fn from_secp256k1_bytes(bytes: &[u8]) -> Result<PublicKey> {
        let public_key = secp256k1::PublicKey::from_slice(bytes)?;
        Ok(PublicKey::Secp256k1(public_key))
    }

    pub fn decode(bytes: &[u8]) -> Result<PublicKey> {
        if bytes.is_empty() {
            return Err(Error::InvalidPublickey);
        }

        let mut encoded_key = bytes.to_vec();
        let ktype = encoded_key.remove(0).try_into()?;
        Self::from_bytes(ktype, &encoded_key)
    }

    pub fn encode(&self) -> Vec<u8> {
        let mut data = vec![self.key_type().into()];
        data.extend(self.to_bytes());
        data
    }

    /// Convert the [`PublicKey`] to a byte array
    pub fn to_bytes(&self) -> Vec<u8> {
        match self {
            PublicKey::Ed25519(public_key) => public_key.to_bytes().to_vec(),
            PublicKey::Secp256k1(public_key) => public_key.serialize().to_vec(),
        }
    }

    pub fn key_type(&self) -> PublicKeyType {
        match self {
            PublicKey::Ed25519(_) => PublicKeyType::Ed25519,
            PublicKey::Secp256k1(_) => PublicKeyType::Secp256k1,
        }
    }
}

impl PublicKey {
    /// Verify the signature of the data provided using [`PrivateKey`]
    pub fn verify(&self, data: &[u8], signature: &[u8]) -> Result<()> {
        match self {
            PublicKey::Ed25519(pubkey) => {
                let signature = Signature::from_bytes(signature)?;
                pubkey.verify(data, &signature)?;
                Ok(())
            }
            PublicKey::Secp256k1(pubkey) => {
                use sha2::Digest;

                let secp = secp256k1::Secp256k1::new();

                let mut hasher = sha2::Sha256::new();
                hasher.update(data);
                let hash = hasher.finalize().to_vec();
                let msg = secp256k1::Message::from_slice(&hash)?;

                let sig = secp256k1::ecdsa::Signature::from_compact(signature)?;
                secp.verify_ecdsa(&msg, &sig, pubkey)?;
                Ok(())
            }
        }
    }
}

impl PublicKey {
    /// Verify the signature of the data from [`std::io::Read`] using [`PrivateKey`]
    pub fn verify_reader(
        &self,
        reader: &mut impl io::Read,
        signature: &[u8],
        context: Option<&[u8]>,
    ) -> Result<()> {
        match self {
            PublicKey::Ed25519(key) => {
                let mut hasher: Sha512 = Sha512::new();
                io::copy(reader, &mut hasher)?;
                let signature = Signature::from_bytes(signature)?;
                key.verify_prehashed(hasher, context, &signature)?;
                Ok(())
            }
            PublicKey::Secp256k1(key) => {
                let secp = secp256k1::Secp256k1::new();
                let mut hasher: Sha512 = Sha512::new();
                io::copy(reader, &mut hasher)?;
                let hash = hasher.finalize().to_vec();
                let msg = secp256k1::Message::from_slice(&hash)?;

                let sig = secp256k1::ecdsa::Signature::from_compact(signature)?;
                secp.verify_ecdsa(&msg, &sig, key)?;
                Ok(())
            }
        }
    }
}
/// [`PrivateKey`] Types
#[derive(Debug, Copy, Clone)]
pub enum PrivateKeyType {
    /// ED25519 Private Key
    Ed25519,

    /// AES-256 Private Key
    Aes256,

    /// Secp256k1 Private Key
    Secp256k1,
}

impl Default for PrivateKeyType {
    fn default() -> Self {
        Self::Ed25519
    }
}

const WRITE_BUFFER_SIZE: usize = 512;
const READ_BUFFER_SIZE: usize = 528;

impl TryFrom<u8> for PrivateKeyType {
    type Error = Error;
    fn try_from(value: u8) -> std::result::Result<Self, Self::Error> {
        match value {
            0xa1 => Ok(PrivateKeyType::Ed25519),
            0xb1 => Ok(PrivateKeyType::Secp256k1),
            0xc1 => Ok(PrivateKeyType::Aes256),
            _ => Err(Error::InvalidPublickey),
        }
    }
}

impl From<PrivateKeyType> for u8 {
    fn from(value: PrivateKeyType) -> Self {
        match value {
            PrivateKeyType::Ed25519 => 0xa1,
            PrivateKeyType::Secp256k1 => 0xb1,
            PrivateKeyType::Aes256 => 0xc1,
        }
    }
}

impl PrivateKey {
    /// Generates a new [`PrivateKey`] with randomly generated key
    pub fn new() -> Self {
        Self::default()
    }

    /// Generate a [`PrivateKey`] using [`PrivateKeyType`]
    pub fn new_with(key_type: PrivateKeyType) -> Self {
        match key_type {
            PrivateKeyType::Ed25519 => {
                let mut csprng = OsRng {};
                let key = ed25519_dalek::Keypair::generate(&mut csprng);
                PrivateKey::Ed25519(key)
            }
            PrivateKeyType::Aes256 => {
                let mut key_sized = [0u8; 32];
                key_sized.copy_from_slice(&generate(32));
                PrivateKey::Aes256(key_sized)
            }
            PrivateKeyType::Secp256k1 => {
                let mut rng = secp256k1::rand::thread_rng();
                PrivateKey::Secp256k1(secp256k1::SecretKey::new(&mut rng))
            }
        }
    }

    /// Import private key which is identified with [`PrivateKeyType`]
    pub fn import(key_type: PrivateKeyType, key: Vec<u8>) -> Result<Self> {
        let key = zeroize::Zeroizing::new(key);
        match key_type {
            PrivateKeyType::Ed25519 => ed25519_dalek::Keypair::from_bytes(&key)
                .map(PrivateKey::Ed25519)
                .map_err(Error::from),
            PrivateKeyType::Aes256 => key
                .as_slice()
                .try_into()
                .map(PrivateKey::Aes256)
                .map_err(Error::from),
            PrivateKeyType::Secp256k1 => secp256k1::SecretKey::from_slice(&key)
                .map(PrivateKey::Secp256k1)
                .map_err(Error::from),
        }
    }

    /// Imports a private key with a identifier to identify if its [`PrivateKey::Ed25519`], [`PrivateKey::Secp256k1`], or [`PrivateKey::Aes256`]
    pub fn decode<B: AsRef<[u8]>>(bytes: B) -> Result<PrivateKey> {
        let bytes = bytes.as_ref();
        if bytes.is_empty() {
            return Err(Error::InvalidPrivatekey);
        }
        let mut encoded_key = bytes.to_vec();
        let ktype = encoded_key.remove(0).try_into()?;
        Self::import(ktype, encoded_key)
    }

    /// Exports the keys out as bytes.
    pub fn to_bytes(&self) -> Vec<u8> {
        match self {
            PrivateKey::Ed25519(kp) => kp.to_bytes().to_vec(),
            PrivateKey::Secp256k1(sk) => sk.secret_bytes().to_vec(),
            PrivateKey::Aes256(key) => key.to_vec(),
        }
    }

    /// Exports the key out with an identifier
    pub fn encode(&self) -> Vec<u8> {
        let mut data = vec![self.key_type().into()];
        data.extend(self.to_bytes());
        data
    }

    /// Provides the [`PrivateKeyType`] of the [`PrivateKey`]
    pub fn key_type(&self) -> PrivateKeyType {
        match self {
            PrivateKey::Aes256(_) => PrivateKeyType::Aes256,
            PrivateKey::Ed25519(_) => PrivateKeyType::Ed25519,
            PrivateKey::Secp256k1(_) => PrivateKeyType::Secp256k1,
        }
    }

    /// Provides the [`PublicKey`] of the [`PrivateKey`]
    /// Note: This will only work with asymmetric keys. Any symmetric keys will
    ///       return [`Error::Unsupported`]
    pub fn public_key(&self) -> Result<PublicKey> {
        match self {
            PrivateKey::Aes256(_) => Err(Error::Unsupported),
            PrivateKey::Ed25519(key) => Ok(key.public.into()),
            PrivateKey::Secp256k1(pk) => {
                let secp = secp256k1::Secp256k1::new();
                Ok(secp256k1::PublicKey::from_secret_key(&secp, pk).into())
            }
        }
    }

    /// Sign the data provided using [`PrivateKey`]
    /// Note: HMAC will be used soon when [`PrivateKeyType::Aes256`] is used
    //TODO: Use HMAC for AES
    pub fn sign<B: AsRef<[u8]>>(&self, data: B) -> Result<Vec<u8>> {
        use sha2::Digest;

        let data = data.as_ref();
        match self {
            PrivateKey::Aes256(_) => {
                let mut hasher = sha2::Sha512::new();
                hasher.update(data);
                let hash = hasher.finalize().to_vec();
                let enc_hash = self.encrypt(&hash, None)?;
                Ok(enc_hash)
            }
            PrivateKey::Ed25519(key) => {
                let signature = key.sign(data);
                Ok(signature.to_bytes().to_vec())
            }
            PrivateKey::Secp256k1(key) => {
                let secp = secp256k1::Secp256k1::new();
                let mut hasher = sha2::Sha256::new();
                hasher.update(data);
                let hash = hasher.finalize().to_vec();
                let msg = secp256k1::Message::from_slice(&hash)?;
                Ok(secp.sign_ecdsa(&msg, key).serialize_compact().to_vec())
            }
        }
    }

    /// Sign the data from [`std::io::Read`] using [`PrivateKey`]
    /// Note: HMAC will be used soon when [`PrivateKeyType::Aes256`] is used
    //TODO: Use HMAC for AES
    pub fn sign_reader(
        &self,
        reader: &mut impl io::Read,
        context: Option<&[u8]>,
    ) -> Result<Vec<u8>> {
        match self {
            PrivateKey::Aes256(_) => {
                let mut hasher: Sha512 = Sha512::new();
                io::copy(reader, &mut hasher)?;
                let hash = hasher.finalize().to_vec();
                let enc_hash = self.encrypt(&hash, None)?;
                Ok(enc_hash)
            }
            PrivateKey::Ed25519(key) => {
                let mut hasher: Sha512 = Sha512::new();
                io::copy(reader, &mut hasher)?;
                let signature = key.sign_prehashed(hasher, context)?;
                Ok(signature.to_bytes().to_vec())
            }
            PrivateKey::Secp256k1(key) => {
                let secp = secp256k1::Secp256k1::new();
                let mut hasher: Sha512 = Sha512::new();
                io::copy(reader, &mut hasher)?;
                let hash = hasher.finalize().to_vec();
                let msg = secp256k1::Message::from_slice(&hash)?;
                Ok(secp.sign_ecdsa(&msg, key).serialize_compact().to_vec())
            }
        }
    }

    /// Verify the signature of the data provided using [`PrivateKey`]
    /// Note: HMAC will be used soon when [`PrivateKeyType::Aes256`] is used
    //TODO: Use HMAC for AES
    pub fn verify(&self, data: &[u8], signature: &[u8]) -> Result<()> {
        match self {
            PrivateKey::Aes256(_) => {
                let mut hasher: Sha512 = Sha512::new();
                hasher.update(data);
                let hash = hasher.finalize().to_vec();
                let dec_hash = self.decrypt(signature, None)?;
                if dec_hash == hash {
                    return Ok(());
                }
                Err(Error::InvalidSignature)
            }
            _ => {
                let public_key = self.public_key()?;
                public_key.verify(data, signature)
            }
        }
    }

    /// Verify the signature of the data from [`std::io::Read`] using [`PrivateKey`]
    /// Note: HMAC will be used soon when [`PrivateKeyType::Aes256`] is used
    //TODO: Use HMAC for AES
    pub fn verify_reader(
        &self,
        reader: &mut impl io::Read,
        signature: &[u8],
        context: Option<&[u8]>,
    ) -> Result<()> {
        match self {
            PrivateKey::Aes256(_) => {
                let mut hasher: Sha512 = Sha512::new();
                io::copy(reader, &mut hasher)?;
                let hash = hasher.finalize().to_vec();
                let dec_hash = self.decrypt(signature, None)?;
                if dec_hash == hash {
                    return Ok(());
                }
                Err(Error::InvalidSignature)
            }
            _ => {
                let public_key = self.public_key()?;
                public_key.verify_reader(reader, signature, context)
            }
        }
    }
}

impl PrivateKey {
    /// Encrypt the data using [`PrivateKey`].
    /// If [`PrivateKeyType::Aes256`] is used, the `pubkey` will be ignored
    pub fn encrypt(&self, data: &[u8], pubkey: Option<PublicKey>) -> Result<Vec<u8>> {
        let key = self.fetch_encryption_key(pubkey)?;
        let raw_nonce = generate(12);
        let key = Key::<Aes256Gcm>::from_slice(&key);
        let nonce = Nonce::from_slice(&raw_nonce);
        let cipher = Aes256Gcm::new(key);
        let mut data = cipher
            .encrypt(nonce, data)
            .map_err(|_| Error::EncryptionError)?;
        data.extend(nonce);
        Ok(data)
    }

    /// Decrypt the data using [`PrivateKey`].
    /// If [`PrivateKeyType::Aes256`] is used, the `pubkey` will be ignored
    pub fn decrypt(&self, data: &[u8], pubkey: Option<PublicKey>) -> Result<Vec<u8>> {
        let key = self.fetch_encryption_key(pubkey)?;
        let (nonce, data) = extract_data_slice(data, 12);
        let key = Key::<Aes256Gcm>::from_slice(&key);
        let nonce = Nonce::from_slice(nonce);
        let cipher = Aes256Gcm::new(key);
        cipher
            .decrypt(nonce, data)
            .map_err(|_| Error::DecryptionError)
    }
}

impl PrivateKey {
    /// Encrypt the data stream from [`std::io::Read`] to [`std::io::Write`] using [`PrivateKey`].
    /// If [`PrivateKeyType::Aes256`] is used, the `pubkey` will be ignored
    pub fn encrypt_stream(
        &self,
        reader: &mut impl io::Read,
        writer: &mut impl io::Write,
        pubkey: Option<PublicKey>,
    ) -> Result<()> {
        let key = self.fetch_encryption_key(pubkey)?;
        let nonce = generate(7);

        let key = Key::<Aes256Gcm>::from_slice(&key);
        let cipher = Aes256Gcm::new(key);
        let mut buffer = [0u8; WRITE_BUFFER_SIZE];
        let mut stream = EncryptorBE32::from_aead(cipher, nonce.as_slice().into());
        writer.write_all(&nonce)?;
        loop {
            match reader.read(&mut buffer) {
                Ok(WRITE_BUFFER_SIZE) => {
                    let ciphertext = stream
                        .encrypt_next(buffer.as_slice())
                        .map_err(|_| Error::EncryptionStreamError)?;
                    writer.write_all(&ciphertext)?;
                }
                Ok(read_count) => {
                    let ciphertext = stream
                        .encrypt_last(&buffer[..read_count])
                        .map_err(|_| Error::EncryptionStreamError)?;
                    writer.write_all(&ciphertext)?;
                    break;
                }
                Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
                Err(e) => return Err(Error::from(e)),
            }
        }
        Ok(())
    }

    /// Decrypt the data stream from [`std::io::Read`] to [`std::io::Write`] using [`PrivateKey`].
    /// If [`PrivateKeyType::Aes256`] is used, the `pubkey` will be ignored
    pub fn decrypt_stream(
        &self,
        reader: &mut impl io::Read,
        writer: &mut impl io::Write,
        pubkey: Option<PublicKey>,
    ) -> Result<()> {
        let key = self.fetch_encryption_key(pubkey)?;
        let mut nonce = vec![0u8; 7];
        reader.read_exact(&mut nonce)?;

        let key = Key::<Aes256Gcm>::from_slice(&key);
        let cipher = Aes256Gcm::new(key);

        let mut stream = DecryptorBE32::from_aead(cipher, nonce.as_slice().into());
        let mut buffer = [0u8; READ_BUFFER_SIZE];
        loop {
            match reader.read(&mut buffer) {
                Ok(READ_BUFFER_SIZE) => {
                    let plaintext = stream
                        .decrypt_next(buffer.as_slice())
                        .map_err(|_| Error::DecryptionStreamError)?;

                    writer.write_all(&plaintext)?
                }
                Ok(read_count) if read_count == 0 => break,
                Ok(read_count) => {
                    let plaintext = stream
                        .decrypt_last(&buffer[..read_count])
                        .map_err(|_| Error::DecryptionStreamError)?;
                    writer.write_all(&plaintext)?;
                    break;
                }
                Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
                Err(e) => return Err(Error::from(e)),
            };
        }
        writer.flush()?;
        Ok(())
    }

    /// Used internally to obtain the encryption key
    fn fetch_encryption_key(&self, pubkey: Option<PublicKey>) -> Result<Vec<u8>> {
        match self {
            PrivateKey::Aes256(key) => Ok(key.to_vec()),
            PrivateKey::Secp256k1(pk) => {
                let public_key: secp256k1::PublicKey = match pubkey {
                    Some(pubkey) => pubkey.try_into()?,
                    None => {
                        let secp = secp256k1::Secp256k1::new();
                        secp256k1::PublicKey::from_secret_key(&secp, pk)
                    }
                };
                let shared_key = secp256k1::ecdh::SharedSecret::new(&public_key, pk);
                Ok(shared_key.as_ref().to_vec())
            }
            PrivateKey::Ed25519(_) => {
                let static_key: x25519_dalek::StaticSecret = self.try_into()?;
                let public_key: x25519_dalek::PublicKey = match pubkey {
                    //Note: This may not be ideal to use one own key for
                    //      performing a ecdh exchange. While there is no known
                    //      attack, we should still be cautious of performing
                    //      this and might be wise in the future to have dual
                    //      keys. One ed25519 and another x25519
                    Some(pubkey) => pubkey.try_into()?,
                    None => x25519_dalek::PublicKey::from(&static_key),
                };
                let enc_key = static_key.diffie_hellman(&public_key);
                Ok(enc_key.as_bytes().to_vec())
            }
        }
    }
}

/// Used internally to split data based on the supplied sized.
fn extract_data_slice(data: &[u8], size: usize) -> (&[u8], &[u8]) {
    let extracted = &data[data.len() - size..];
    let payload = &data[..data.len() - size];
    (extracted, payload)
}

/// Used to generate random amount of data and store it in a Vec with a specific capacity
fn generate(size: usize) -> Vec<u8> {
    use rand::RngCore;
    let mut buffer = vec![0u8; size];
    OsRng.fill_bytes(&mut buffer);
    buffer
}