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
use crate::crypto::cipher::{CipherCategory, CipherResult, CipherType};
use crate::crypto::ring::RingAeadCipher;
#[cfg(feature = "miscreant")]
use crate::crypto::siv::MiscreantCipher;
#[cfg(feature = "sodium")]
use crate::crypto::sodium::SodiumAeadCipher;
use bytes::{Bytes, BytesMut};
use ring::{digest::SHA1, hkdf, hmac::SigningKey};
pub trait AeadEncryptor {
fn encrypt(&mut self, input: &[u8], output: &mut [u8]);
}
pub trait AeadDecryptor {
fn decrypt(&mut self, input: &[u8], output: &mut [u8]) -> CipherResult<()>;
}
pub type BoxAeadDecryptor = Box<AeadDecryptor + Send + 'static>;
pub type BoxAeadEncryptor = Box<AeadEncryptor + Send + 'static>;
pub fn new_aead_encryptor(t: CipherType, key: &[u8], nonce: &[u8]) -> BoxAeadEncryptor {
assert!(t.category() == CipherCategory::Aead);
match t {
CipherType::Aes128Gcm | CipherType::Aes256Gcm | CipherType::ChaCha20IetfPoly1305 => {
Box::new(RingAeadCipher::new(t, key, nonce, true))
}
#[cfg(feature = "sodium")]
CipherType::XChaCha20IetfPoly1305 => Box::new(SodiumAeadCipher::new(t, key, nonce)),
#[cfg(feature = "miscreant")]
CipherType::Aes128PmacSiv | CipherType::Aes256PmacSiv => Box::new(MiscreantCipher::new(t, key, nonce)),
_ => unreachable!(),
}
}
pub fn new_aead_decryptor(t: CipherType, key: &[u8], nonce: &[u8]) -> BoxAeadDecryptor {
assert!(t.category() == CipherCategory::Aead);
match t {
CipherType::Aes128Gcm | CipherType::Aes256Gcm | CipherType::ChaCha20IetfPoly1305 => {
Box::new(RingAeadCipher::new(t, key, nonce, false))
}
#[cfg(feature = "sodium")]
CipherType::XChaCha20IetfPoly1305 => Box::new(SodiumAeadCipher::new(t, key, nonce)),
#[cfg(feature = "miscreant")]
CipherType::Aes128PmacSiv | CipherType::Aes256PmacSiv => Box::new(MiscreantCipher::new(t, key, nonce)),
_ => unreachable!(),
}
}
const SUBKEY_INFO: &[u8] = b"ss-subkey";
pub fn make_skey(t: CipherType, key: &[u8], salt: &[u8]) -> Bytes {
assert!(t.category() == CipherCategory::Aead);
let salt = SigningKey::new(&SHA1, salt);
let mut skey = BytesMut::with_capacity(key.len());
unsafe {
skey.set_len(key.len());
}
hkdf::extract_and_expand(&salt, key, SUBKEY_INFO, &mut skey);
skey.freeze()
}
#[cfg(feature = "sodium")]
pub fn increase_nonce(nonce: &mut [u8]) {
use libsodium_ffi::sodium_increment;
unsafe {
sodium_increment(nonce.as_mut_ptr(), nonce.len());
}
}
#[cfg(not(feature = "sodium"))]
pub fn increase_nonce(nonce: &mut [u8]) {
let mut prev: u16 = 1;
for i in nonce {
prev += *i as u16;
*i = prev as u8;
prev >>= 8;
}
}