Skip to main content

over_there/core/transport/crypto/
mod.rs

1pub mod aes;
2pub use aes::{
3    Aes128GcmBicrypter, Aes128GcmSivBicrypter, Aes128SivBicrypter,
4    Aes256GcmBicrypter, Aes256GcmSivBicrypter, Aes256SivBicrypter, AesError,
5};
6
7pub mod nonce;
8pub use nonce::{Nonce, Nonce128Bits, Nonce96Bits, NonceSize};
9
10pub mod key;
11pub use key::{Key128Bits, Key256Bits, Key512Bits, KeySize};
12
13mod noop;
14pub use noop::NoopBicrypter;
15
16mod closure;
17pub use closure::{ClosureDecrypter, ClosureEncrypter};
18
19pub mod split;
20
21use derive_more::{Display, Error};
22use serde::{Deserialize, Serialize};
23
24#[derive(Debug, Display, Error)]
25pub enum CryptError {
26    /// Internal Error related to encryption occurred
27    EncryptFailed(#[error(ignore)] String),
28
29    /// Internal Error related to decryption occurred
30    DecryptFailed(#[error(ignore)] String),
31
32    /// Contains the nonce that was already used
33    #[display(fmt = "nonce:{:?}", nonce)]
34    NonceAlreadyUsed { nonce: Vec<u8> },
35
36    /// Contains size of nonce provided
37    NonceWrongSize { provided_size: usize },
38
39    /// When a nonce was expected and none was provided
40    MissingNonce,
41}
42
43#[derive(Serialize, Deserialize, Debug, Clone)]
44pub enum AssociatedData {
45    None,
46    Nonce(Nonce),
47}
48
49impl AssociatedData {
50    pub fn nonce(&self) -> Option<&Nonce> {
51        match self {
52            AssociatedData::None => None,
53            AssociatedData::Nonce(nonce) => Some(nonce),
54        }
55    }
56
57    pub fn nonce_slice(&self) -> Option<&[u8]> {
58        self.nonce().map(|n| n.as_slice())
59    }
60}
61
62impl From<Nonce> for AssociatedData {
63    fn from(nonce: Nonce) -> Self {
64        Self::Nonce(nonce)
65    }
66}
67
68impl From<Option<Nonce>> for AssociatedData {
69    fn from(nonce: Option<Nonce>) -> Self {
70        match nonce {
71            None => Self::None,
72            Some(nonce) => Self::Nonce(nonce),
73        }
74    }
75}
76
77impl From<NonceSize> for AssociatedData {
78    fn from(nonce_size: NonceSize) -> Self {
79        Self::from(Nonce::from(nonce_size))
80    }
81}
82
83/// Can both encrypt and decrypt
84pub trait Bicrypter: Encrypter + Decrypter {}
85
86/// Capable of encrypting data
87pub trait Encrypter {
88    fn encrypt(
89        &self,
90        buffer: &[u8],
91        associated_data: &AssociatedData,
92    ) -> Result<Vec<u8>, CryptError>;
93
94    /// Encrypter generates its own associated data, useful for producing
95    /// a new nonce, etc.
96    fn new_encrypt_associated_data(&self) -> AssociatedData;
97}
98
99/// Capable of decrypting data
100pub trait Decrypter {
101    fn decrypt(
102        &self,
103        buffer: &[u8],
104        associated_data: &AssociatedData,
105    ) -> Result<Vec<u8>, CryptError>;
106}