-
Notifications
You must be signed in to change notification settings - Fork 2
/
encrypted.rs
163 lines (133 loc) · 5.11 KB
/
encrypted.rs
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
use crate::errors::PortalError::*;
use serde::{Deserialize, Serialize};
use std::convert::TryInto;
use std::error::Error;
// Nonce generation
use rand::Rng;
// Encryption
#[cfg(not(feature = "ring-backend"))]
use chacha20poly1305::{aead::AeadInPlace, aead::NewAead, ChaCha20Poly1305, Key, Nonce, Tag};
#[cfg(feature = "ring-backend")]
use ring::aead::{Aad, LessSafeKey, Nonce, Tag, UnboundKey, CHACHA20_POLY1305};
/// We store 128bits but only need 96bit nonces
const NONCE_SIZE: usize = 12;
const TAG_SIZE: usize = 16;
/// An abstraction around a nonce sequence. Safely
/// ensures there is no nonce re-use during a session
/// with a single key.
pub struct NonceSequence([u8; TAG_SIZE]);
/// All encrypted messages must have associated state data (nonce, tag)
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone, Default)]
pub struct EncryptedMessage {
/// Provides storage for chacha20poly1305::Nonce
pub nonce: [u8; NONCE_SIZE],
/// Provides storage for chacha20poly1305::Tag
pub tag: [u8; TAG_SIZE],
/// Length of follow-on data. Data is not owned
/// directly to prevent copies
pub len: usize,
}
#[cfg(not(feature = "ring-backend"))]
impl EncryptedMessage {
/// Create an encrypted message out of an arbitrary serializable
/// type
pub fn encrypt(
key: &[u8],
nseq: &mut NonceSequence,
data: &mut [u8],
) -> Result<Self, Box<dyn Error>> {
// Init state to send
let mut state = Self::default();
// Obtain the next nonce
state.nonce = nseq.next()?;
let nonce = Nonce::from_slice(&state.nonce);
// Obtain the cipher from the key
let cha_key = Key::from_slice(&key[..]);
let cipher = ChaCha20Poly1305::new(cha_key);
// Set the length
state.len = data.len();
// Encrypt the data in-place
let tag = cipher
.encrypt_in_place_detached(nonce, b"", data)
.or(Err(EncryptError))?;
// Save the tag in our current state
state.tag = tag.into();
Ok(state)
}
/// Decrypt the provided data in-place
pub fn decrypt(&mut self, key: &[u8], data: &mut [u8]) -> Result<usize, Box<dyn Error>> {
// Obtain the cipher from the key
let cha_key = Key::from_slice(&key[..]);
let cipher = ChaCha20Poly1305::new(cha_key);
// The nonce & tag are self contained
let nonce = Nonce::from_slice(&self.nonce);
let tag = Tag::from_slice(&self.tag);
// Decrypt the data in place
cipher
.decrypt_in_place_detached(&nonce, b"", data, &tag)
.or(Err(DecryptError))?;
Ok(data.len())
}
}
#[cfg(feature = "ring-backend")]
impl EncryptedMessage {
/// Create an encrypted message out of an arbitrary serializable
/// type
pub fn encrypt(
key: &[u8],
nseq: &mut NonceSequence,
data: &mut [u8],
) -> Result<Self, Box<dyn Error>> {
// Init state to send
let mut state = Self::default();
// Init the key
let ring_key_chacha20 =
LessSafeKey::new(UnboundKey::new(&CHACHA20_POLY1305, key).or(Err(CryptoError))?);
// Obtain the next nonce
state.nonce = nseq.next()?;
let ring_nonce = Nonce::assume_unique_for_key(state.nonce);
// Set the length
state.len = data.len();
// Encrypt the data in-place. For ring we must append the tag after
let tag = ring_key_chacha20
.seal_in_place_separate_tag(ring_nonce, Aad::empty(), data)
.or(Err(EncryptError))?;
// Save the tag in our current state
state.tag = tag.as_ref().try_into().or(Err(EncryptError))?;
Ok(state)
}
/// Decrypt the provided data in-place
pub fn decrypt(&mut self, key: &[u8], data: &mut [u8]) -> Result<usize, Box<dyn Error>> {
// Init the key
let ring_key_chacha20 =
LessSafeKey::new(UnboundKey::new(&CHACHA20_POLY1305, key).or(Err(CryptoError))?);
// The nonce & tag are self contained
let ring_tag: Tag = self.tag.try_into().or(Err(DecryptError))?;
let ring_nonce = Nonce::assume_unique_for_key(self.nonce);
// Decrypt the data in place
ring_key_chacha20
.open_in_place_separate_tag(ring_nonce, Aad::empty(), ring_tag, data, 0..)
.or(Err(DecryptError))?;
Ok(data.len())
}
}
impl NonceSequence {
/// Initialize the sequence by generating a random 128bit nonce
pub fn new() -> Self {
let mut rng = rand::thread_rng();
Self {
0: rng.gen::<[u8; 16]>(),
}
}
/// Advance the sequence by incrementing the internal state
/// and returning the current state. Similar nonces in TLS 1.3
pub fn next(&mut self) -> Result<[u8; NONCE_SIZE], Box<dyn Error>> {
// Save the old value
let old = self.0;
// Increment & store the new value
let new = u128::from_be_bytes(self.0).wrapping_shr(32);
self.0 = new.wrapping_add(1).wrapping_shl(32).to_be_bytes();
// Return the old value as a nonce
old[..NONCE_SIZE].try_into().or(Err(CryptoError.into()))
}
}