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
pub mod aead;
pub use crate::aead::{
AeadError, Aes128GcmBicrypter, Aes128GcmSivBicrypter, Aes128SivBicrypter,
Aes256GcmBicrypter, Aes256GcmSivBicrypter, Aes256SivBicrypter,
};
pub mod nonce;
pub use nonce::{Nonce, Nonce128Bits, Nonce96Bits, NonceSize};
pub mod key;
pub use key::{Key128Bits, Key256Bits, Key512Bits, KeySize};
mod noop;
pub use noop::NoopBicrypter;
mod closure;
pub use closure::{ClosureDecrypter, ClosureEncrypter};
pub mod split;
use over_there_derive::Error;
use serde::{Deserialize, Serialize};
#[derive(Debug, Error)]
pub enum CryptError {
EncryptFailed(String),
DecryptFailed(String),
NonceAlreadyUsed { nonce: Vec<u8> },
NonceWrongSize { provided_size: usize },
MissingNonce,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum AssociatedData {
None,
Nonce(Nonce),
}
impl AssociatedData {
pub fn nonce(&self) -> Option<&Nonce> {
match self {
AssociatedData::None => None,
AssociatedData::Nonce(nonce) => Some(nonce),
}
}
pub fn nonce_slice(&self) -> Option<&[u8]> {
self.nonce().map(|n| n.as_slice())
}
}
impl From<Nonce> for AssociatedData {
fn from(nonce: Nonce) -> Self {
Self::Nonce(nonce)
}
}
impl From<Option<Nonce>> for AssociatedData {
fn from(nonce: Option<Nonce>) -> Self {
match nonce {
None => Self::None,
Some(nonce) => Self::Nonce(nonce),
}
}
}
impl From<NonceSize> for AssociatedData {
fn from(nonce_size: NonceSize) -> Self {
Self::from(Nonce::from(nonce_size))
}
}
pub trait Bicrypter: Encrypter + Decrypter {}
pub trait Encrypter {
fn encrypt(
&self,
buffer: &[u8],
associated_data: &AssociatedData,
) -> Result<Vec<u8>, CryptError>;
fn new_encrypt_associated_data(&self) -> AssociatedData;
}
pub trait Decrypter {
fn decrypt(
&self,
buffer: &[u8],
associated_data: &AssociatedData,
) -> Result<Vec<u8>, CryptError>;
}