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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
use errors::CoreError;
use rand::{OsRng, Rng};
use routing::{EntryAction, Value, XorName};
use rust_sodium::crypto::secretbox;
use std::collections::{BTreeMap, BTreeSet};
use tiny_keccak::sha3_256;
use utils::{symmetric_decrypt, symmetric_encrypt};
const REENCRYPT_ERROR: &'static str = "Cannot reencrypt without new_enc_info";
const DECRYPT_ERROR: &'static str = "Cannot decrypt without new_enc_info";
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct MDataInfo {
pub name: XorName,
pub type_tag: u64,
pub enc_info: Option<(secretbox::Key, Option<secretbox::Nonce>)>,
pub new_enc_info: Option<(secretbox::Key, Option<secretbox::Nonce>)>,
}
impl MDataInfo {
pub fn new_private(
name: XorName,
type_tag: u64,
enc_info: (secretbox::Key, Option<secretbox::Nonce>),
) -> Self {
MDataInfo {
name,
type_tag,
enc_info: Some(enc_info),
new_enc_info: None,
}
}
pub fn new_public(name: XorName, type_tag: u64) -> Self {
MDataInfo {
name,
type_tag,
enc_info: None,
new_enc_info: None,
}
}
pub fn random_private(type_tag: u64) -> Result<Self, CoreError> {
let mut rng = os_rng()?;
let enc_info = (secretbox::gen_key(), Some(secretbox::gen_nonce()));
Ok(Self::new_private(rng.gen(), type_tag, enc_info))
}
pub fn random_public(type_tag: u64) -> Result<Self, CoreError> {
let mut rng = os_rng()?;
Ok(Self::new_public(rng.gen(), type_tag))
}
pub fn enc_key(&self) -> Option<&secretbox::Key> {
self.enc_info.as_ref().map(|&(ref key, _)| key)
}
pub fn enc_entry_key(&self, plain_text: &[u8]) -> Result<Vec<u8>, CoreError> {
if let Some((ref key, seed)) = self.enc_info {
enc_entry_key(plain_text, key, seed)
} else {
Ok(plain_text.to_vec())
}
}
pub fn enc_entry_value(&self, plain_text: &[u8]) -> Result<Vec<u8>, CoreError> {
if let Some((ref key, _)) = self.enc_info {
symmetric_encrypt(plain_text, key, None)
} else {
Ok(plain_text.to_vec())
}
}
pub fn decrypt(&self, cipher: &[u8]) -> Result<Vec<u8>, CoreError> {
if let Some((ref key, _)) = self.enc_info {
symmetric_decrypt(cipher, key)
} else {
Ok(cipher.to_vec())
}
}
pub fn decrypt_new_enc_info(&self, cipher: &[u8]) -> Result<Vec<u8>, CoreError> {
if let Some((ref key, _)) = self.new_enc_info {
symmetric_decrypt(cipher, key)
} else {
Err(CoreError::from(DECRYPT_ERROR))
}
}
pub fn start_new_enc_info(&mut self) {
if self.enc_info.is_some() {
self.new_enc_info = Some((secretbox::gen_key(), Some(secretbox::gen_nonce())));
}
}
pub fn commit_new_enc_info(&mut self) {
if let Some(new_enc_info) = self.new_enc_info.take() {
self.enc_info = Some(new_enc_info);
}
}
pub fn abort_new_enc_info(&mut self) {
self.new_enc_info = None;
}
pub fn reencrypt_entry_key(&self, cipher: &[u8]) -> Result<Vec<u8>, CoreError> {
if let Some((ref new_key, new_nonce)) = self.new_enc_info {
let plain_text = self.decrypt(cipher)?;
enc_entry_key(&plain_text, new_key, new_nonce)
} else {
Err(CoreError::from(REENCRYPT_ERROR))
}
}
pub fn reencrypt_entry_value(&self, cipher: &[u8]) -> Result<Vec<u8>, CoreError> {
if let Some((ref new_key, _)) = self.new_enc_info {
let plain_text = self.decrypt(cipher)?;
symmetric_encrypt(&plain_text, new_key, None)
} else {
Err(CoreError::from(REENCRYPT_ERROR))
}
}
}
fn os_rng() -> Result<OsRng, CoreError> {
OsRng::new().map_err(|_| CoreError::RandomDataGenerationFailure)
}
pub fn encrypt_entries(
info: &MDataInfo,
entries: &BTreeMap<Vec<u8>, Value>,
) -> Result<BTreeMap<Vec<u8>, Value>, CoreError> {
let mut output = BTreeMap::new();
for (key, value) in entries {
let encrypted_key = info.enc_entry_key(key)?;
let encrypted_value = encrypt_value(info, value)?;
let _ = output.insert(encrypted_key, encrypted_value);
}
Ok(output)
}
pub fn encrypt_entry_actions(
info: &MDataInfo,
actions: &BTreeMap<Vec<u8>, EntryAction>,
) -> Result<BTreeMap<Vec<u8>, EntryAction>, CoreError> {
let mut output = BTreeMap::new();
for (key, action) in actions {
let encrypted_key = info.enc_entry_key(key)?;
let encrypted_action = match *action {
EntryAction::Ins(ref value) => EntryAction::Ins(encrypt_value(info, value)?),
EntryAction::Update(ref value) => EntryAction::Update(encrypt_value(info, value)?),
EntryAction::Del(version) => EntryAction::Del(version),
};
let _ = output.insert(encrypted_key, encrypted_action);
}
Ok(output)
}
pub fn decrypt_entries(
info: &MDataInfo,
entries: &BTreeMap<Vec<u8>, Value>,
) -> Result<BTreeMap<Vec<u8>, Value>, CoreError> {
let mut output = BTreeMap::new();
for (key, value) in entries {
let decrypted_key = info.decrypt(key)?;
let decrypted_value = decrypt_value(info, value)?;
let _ = output.insert(decrypted_key, decrypted_value);
}
Ok(output)
}
pub fn decrypt_keys(
info: &MDataInfo,
keys: &BTreeSet<Vec<u8>>,
) -> Result<BTreeSet<Vec<u8>>, CoreError> {
let mut output = BTreeSet::new();
for key in keys {
let _ = output.insert(info.decrypt(key)?);
}
Ok(output)
}
pub fn decrypt_values(info: &MDataInfo, values: &[Value]) -> Result<Vec<Value>, CoreError> {
let mut output = Vec::with_capacity(values.len());
for value in values {
output.push(decrypt_value(info, value)?);
}
Ok(output)
}
fn encrypt_value(info: &MDataInfo, value: &Value) -> Result<Value, CoreError> {
Ok(Value {
content: info.enc_entry_value(&value.content)?,
entry_version: value.entry_version,
})
}
fn decrypt_value(info: &MDataInfo, value: &Value) -> Result<Value, CoreError> {
Ok(Value {
content: info.decrypt(&value.content)?,
entry_version: value.entry_version,
})
}
fn enc_entry_key(
plain_text: &[u8],
key: &secretbox::Key,
seed: Option<secretbox::Nonce>,
) -> Result<Vec<u8>, CoreError> {
let nonce = match seed {
Some(secretbox::Nonce(ref nonce)) => {
let mut pt = plain_text.to_vec();
pt.extend_from_slice(&nonce[..]);
unwrap!(secretbox::Nonce::from_slice(
&sha3_256(&pt)[..secretbox::NONCEBYTES],
))
}
None => secretbox::gen_nonce(),
};
symmetric_encrypt(plain_text, key, Some(&nonce))
}
#[cfg(test)]
mod tests {
use super::*;
use rand;
use rust_sodium::crypto::secretbox;
#[test]
fn private_mdata_info_encrypts() {
let info = unwrap!(MDataInfo::random_private(0));
let key = Vec::from("str of key");
let val = Vec::from("other is value");
let enc_key = unwrap!(info.enc_entry_key(&key));
let enc_val = unwrap!(info.enc_entry_value(&val));
assert_ne!(enc_key, key);
assert_ne!(enc_val, val);
assert_eq!(unwrap!(info.decrypt(&enc_key)), key);
assert_eq!(unwrap!(info.decrypt(&enc_val)), val);
}
#[test]
fn public_mdata_info_doesnt_encrypt() {
let info = unwrap!(MDataInfo::random_public(0));
let key = Vec::from("str of key");
let val = Vec::from("other is value");
assert_eq!(unwrap!(info.enc_entry_key(&key)), key);
assert_eq!(unwrap!(info.enc_entry_value(&val)), val);
assert_eq!(unwrap!(info.decrypt(&val)), val);
}
#[test]
fn no_nonce_means_random_nonce() {
let info = MDataInfo {
name: rand::random(),
type_tag: 0,
enc_info: Some((secretbox::gen_key(), None)),
new_enc_info: None,
};
let key = Vec::from("str of key");
let enc_key = unwrap!(info.enc_entry_key(&key));
assert_ne!(enc_key, key);
assert_ne!(unwrap!(info.enc_entry_key(&key)), key);
}
}