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
use crate::{Error, Result};
use core::{fmt, str};
use encoding::Label;
#[cfg(feature = "encryption")]
use aes::{
cipher::{InnerIvInit, KeyInit, StreamCipherCore},
Aes256,
};
const AES256_CTR: &str = "aes256-ctr";
#[cfg(feature = "encryption")]
type Ctr128BE<Cipher> = ctr::CtrCore<Cipher, ctr::flavors::Ctr128BE>;
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum Cipher {
None,
Aes256Ctr,
}
impl Cipher {
pub fn new(ciphername: &str) -> Result<Self> {
match ciphername {
"none" => Ok(Self::None),
AES256_CTR => Ok(Self::Aes256Ctr),
_ => Err(Error::Algorithm),
}
}
pub fn as_str(self) -> &'static str {
match self {
Self::None => "none",
Self::Aes256Ctr => AES256_CTR,
}
}
pub fn key_and_iv_size(self) -> Option<(usize, usize)> {
match self {
Self::None => None,
Self::Aes256Ctr => Some((32, 16)),
}
}
pub fn block_size(self) -> usize {
match self {
Self::None => 8,
Self::Aes256Ctr => 16,
}
}
#[allow(clippy::integer_arithmetic)]
pub fn padding_len(self, input_size: usize) -> usize {
match input_size % self.block_size() {
0 => 0,
input_rem => self.block_size() - input_rem,
}
}
pub fn is_none(self) -> bool {
self == Self::None
}
pub fn is_some(self) -> bool {
!self.is_none()
}
#[cfg(feature = "encryption")]
#[cfg_attr(docsrs, doc(cfg(feature = "encryption")))]
pub fn decrypt(self, key: &[u8], iv: &[u8], buffer: &mut [u8]) -> Result<()> {
match self {
Self::None => return Err(Error::Crypto),
Self::Aes256Ctr => self.encrypt(key, iv, buffer)?,
}
Ok(())
}
#[cfg(feature = "encryption")]
#[cfg_attr(docsrs, doc(cfg(feature = "encryption")))]
pub fn encrypt(self, key: &[u8], iv: &[u8], buffer: &mut [u8]) -> Result<()> {
match self {
Self::None => return Err(Error::Crypto),
Self::Aes256Ctr => {
let cipher = Aes256::new_from_slice(key)
.and_then(|aes| Ctr128BE::inner_iv_slice_init(aes, iv))
.map_err(|_| Error::Crypto)?;
cipher
.try_apply_keystream_partial(buffer.into())
.map_err(|_| Error::Crypto)?;
}
}
Ok(())
}
}
impl AsRef<str> for Cipher {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl Label for Cipher {
type Error = Error;
}
impl Default for Cipher {
fn default() -> Cipher {
Cipher::Aes256Ctr
}
}
impl fmt::Display for Cipher {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl str::FromStr for Cipher {
type Err = Error;
fn from_str(id: &str) -> Result<Self> {
Self::new(id)
}
}