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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
pub mod errors;
pub mod traits;
pub use errors::EnclaveError;
pub use traits::{Decryptable, Encryptable};
pub use secured_cipher::{
algorithm::chacha20::CHACHA20_NONCE_SIZE, random_bytes, Cipher, Key, KeyDerivationStrategy,
SignedEnvelope,
};
const KEY_SIZE: usize = 32;
const NONCE_SIZE: usize = CHACHA20_NONCE_SIZE;
/// `Enclave` acts as a container for encrypted data, including metadata and the encrypted content itself.
///
/// Metadata is unencrypted and can be used to store information about the data,
/// while the actual data is securely encrypted.
///
/// # Type Parameters
/// * `T`: The type of metadata associated with the encrypted data.
#[derive(Debug, Clone)]
pub struct Enclave<T> {
/// Metadata associated with the encrypted data.
pub metadata: T,
/// The encrypted data.
pub encrypted_bytes: Box<[u8]>,
/// The nonce used in the encryption process, 8 bytes long (ChaCha20).
pub nonce: [u8; NONCE_SIZE],
}
impl<T> Enclave<T>
where
T: TryFrom<Vec<u8>> + Into<Vec<u8>> + Clone,
{
/// Creates a new `Enclave` instance from unencrypted data.
///
/// # Arguments
/// * `metadata`: The metadata to be associated with the encrypted data.
/// * `key`: A 32-byte cipher key used for encryption.
/// * `plain_bytes`: The data to be encrypted.
///
/// # Returns
/// A `Result` containing the newly created `Enclave` instance, or an error string if encryption fails.
pub fn from_plain_bytes(
metadata: T,
key: [u8; KEY_SIZE],
plain_bytes: Vec<u8>,
) -> Result<Self, String> {
let nonce = random_bytes::<NONCE_SIZE>();
let mut cipher = Cipher::default();
cipher.init(&key, &nonce);
let encrypted_bytes = cipher.encrypt(&plain_bytes);
let envelope: Vec<u8> = cipher
.sign(&metadata.clone().into(), &encrypted_bytes)
.into();
Ok(Enclave {
metadata,
encrypted_bytes: envelope.into_boxed_slice(),
nonce,
})
}
/// Decrypts the contents of the enclave using a provided key.
///
/// # Arguments
/// * `key`: The 32-byte cipher key used for decryption.
///
/// # Returns
/// A `Result` containing the decrypted data as a vector of bytes, or an error string if decryption fails.
pub fn decrypt(&self, key: [u8; KEY_SIZE]) -> Result<Vec<u8>, EnclaveError> {
let envelope = SignedEnvelope::from(self.encrypted_bytes.to_vec());
Ok(
Cipher::default()
.init(&key, &self.nonce)
.decrypt_and_verify(&envelope)?,
)
}
/// Recovers the key used to encrypt the enclave using a provided password.
///
/// # Arguments
/// * `encrypted_bytes`: The encrypted enclave.
///
/// # Returns
/// A `Result` containing the recovered key, or an error string if recovery fails.
pub fn recover_key(
encrypted_bytes: &[u8],
password: &[u8],
) -> Result<Key<KEY_SIZE, 16>, EnclaveError> {
let strategy = KeyDerivationStrategy::try_from(
encrypted_bytes[encrypted_bytes.len() - 9..encrypted_bytes.len()].to_vec(),
)?;
let salt: [u8; 16] = encrypted_bytes[encrypted_bytes.len() - 25..encrypted_bytes.len() - 9]
.try_into()
.unwrap();
let key = Key::<KEY_SIZE, 16>::with_salt(password, salt, strategy);
Ok(key)
}
}
impl<T> From<Enclave<T>> for Vec<u8>
where
T: TryFrom<Vec<u8>> + Into<Vec<u8>>,
{
/// Serializes an `Enclave` instance into a byte vector.
///
/// # Arguments
/// * `enclave`: The `Enclave` instance to be serialized.
///
/// # Returns
/// A `Vec<u8>` representing the serialized enclave.
fn from(enclave: Enclave<T>) -> Vec<u8> {
let mut bytes: Vec<u8> = vec![];
let metadata_bytes = enclave.metadata.into();
bytes.append(&mut vec![u8::try_from(metadata_bytes.len()).unwrap()]);
bytes.append(&mut metadata_bytes.into());
bytes.append(&mut enclave.encrypted_bytes.into());
bytes.append(&mut enclave.nonce.to_vec());
bytes
}
}
impl<T> TryFrom<Vec<u8>> for Enclave<T>
where
T: TryFrom<Vec<u8>> + Into<Vec<u8>>,
{
type Error = EnclaveError;
/// Deserializes a byte vector into an `Enclave` instance.
///
/// # Arguments
/// * `bytes`: The byte vector representing the serialized enclave.
///
/// # Returns
/// A `Result` containing the deserialized `Enclave` instance, or an `EnclaveError` if deserialization fails.
fn try_from(bytes: Vec<u8>) -> Result<Self, EnclaveError> {
if bytes.len() == 0 {
return Err(EnclaveError::Deserialization("No bytes found".to_string()));
}
let metadata_len = bytes[0];
if usize::from(metadata_len) > bytes.len() {
return Err(EnclaveError::Deserialization(
"unexpected metadata length".to_string(),
));
}
let metadata = T::try_from(bytes[1..metadata_len as usize + 1].to_vec()).or(Err(
EnclaveError::Deserialization("error deserializing metadata".to_string()),
))?;
let encrypted_bytes = bytes[metadata_len as usize + 1..bytes.len() - NONCE_SIZE].to_vec();
let nonce = bytes[bytes.len() - NONCE_SIZE..bytes.len()].to_vec();
Ok(Enclave {
metadata,
encrypted_bytes: encrypted_bytes.into_boxed_slice(),
nonce: nonce.try_into().or(Err(EnclaveError::Deserialization(
"unexpected bytes length".to_string(),
)))?,
})
}
}
impl<T> PartialEq for Enclave<T>
where
T: PartialEq + TryFrom<Vec<u8>> + Into<Vec<u8>>,
{
/// Compares two `Enclave` instances for equality.
///
/// # Arguments
/// * `other`: Another `Enclave` instance to compare with.
///
/// # Returns
/// `true` if both `Enclave` instances are equal, `false` otherwise.
fn eq(&self, other: &Self) -> bool {
self.metadata == other.metadata
&& self.encrypted_bytes == other.encrypted_bytes
&& self.nonce == other.nonce
}
}
impl Encryptable<KEY_SIZE> for Vec<u8> {
/// Encrypts a vector of bytes using a provided password.
///
/// # Arguments
/// * `password`: The password to use for key derivation.
/// * `strategy`: The key derivation strategy to use.
///
/// # Returns
/// A `Vec<u8>` containing the encrypted data.
fn encrypt(&self, password: String, strategy: KeyDerivationStrategy) -> Vec<u8> {
let key: Key<32, 16> = Key::new(password.as_bytes(), strategy.clone());
let enclave = Enclave::from_plain_bytes(vec![], key.pubk, self.clone()).unwrap();
[enclave.into(), key.salt.to_vec(), strategy.into()].concat()
}
/// Encrypts a vector of bytes using a provided key.
///
/// # Arguments
/// * `key`: The 32-byte cipher key used for encryption.
///
/// # Returns
/// A `Vec<u8>` containing the encrypted data.
fn encrypt_with_key(&self, key: &Key<32, 16>) -> Vec<u8> {
let enclave = Enclave::from_plain_bytes(vec![], key.pubk, self.clone()).unwrap();
[
enclave.into(),
key.salt.to_vec(),
key.strategy.clone().into(),
]
.concat()
}
/// Encrypts a vector of bytes using a provided key.
///
/// # Arguments
/// * `key`: The 32-byte cipher key used for encryption.
///
/// # Returns
/// A `Vec<u8>` containing the encrypted data.
fn encrypt_with_raw_key(&self, key: [u8; KEY_SIZE]) -> Vec<u8> {
let enclave = Enclave::from_plain_bytes(vec![], key, self.clone()).unwrap();
enclave.into()
}
/// Encrypts a vector of bytes using a provided key and metadata.
///
/// # Arguments
/// * `key`: The 32-byte cipher key used for encryption.
/// * `metadata`: The metadata to be associated with the encrypted data.
///
/// # Returns
/// A `Vec<u8>` containing the encrypted data.
fn encrypt_with_metadata<M>(&self, key: [u8; KEY_SIZE], metadata: M) -> Vec<u8>
where
M: From<Vec<u8>> + Into<Vec<u8>> + Clone,
{
let enclave = Enclave::from_plain_bytes(metadata, key, self.clone()).unwrap();
enclave.into()
}
}
impl Decryptable<KEY_SIZE> for Vec<u8> {
/// Decrypts a slice of bytes using a provided password.
///
/// # Arguments
/// * `password`: The password to use for decryption.
///
/// # Returns
/// A `Result` containing the decrypted data as a vector of bytes, or an error string if decryption fails.
fn decrypt(&self, password: String) -> Result<Vec<u8>, EnclaveError> {
let strategy = KeyDerivationStrategy::try_from(self[self.len() - 9..self.len()].to_vec())?;
let salt: [u8; 16] = self[self.len() - 25..self.len() - 9].try_into().unwrap();
let key = Key::<KEY_SIZE, 16>::with_salt(password.as_bytes(), salt, strategy);
let enclave = Enclave::<Vec<u8>>::try_from(self[..self.len() - 25].to_vec())?;
enclave.decrypt(key.pubk)
}
/// Decrypts a slice of bytes using a provided key.
///
/// # Arguments
/// * `key`: The 32-byte cipher key used for decryption.
///
/// # Returns
/// A `Result` containing the decrypted data as a vector of bytes, or an error string if decryption fails.
fn decrypt_with_key(&self, key: [u8; KEY_SIZE]) -> Result<Vec<u8>, EnclaveError> {
let enclave = Enclave::<Vec<u8>>::try_from(self.clone())?;
enclave.decrypt(key)
}
/// Decrypts a slice of bytes using a provided key.
///
/// # Arguments
/// * `key`: The 32-byte cipher key used for decryption.
///
/// # Returns
/// A `Result` containing the decrypted data as a vector of bytes, or an error string if decryption fails.
fn decrypt_with_metadata<M>(&self, key: [u8; KEY_SIZE]) -> Result<(Vec<u8>, M), EnclaveError>
where
M: TryFrom<Vec<u8>> + Into<Vec<u8>> + Clone,
{
let enclave = Enclave::<M>::try_from(self.clone())?;
let decrypted_bytes = enclave.decrypt(key)?;
Ok((decrypted_bytes, enclave.metadata))
}
}
impl Decryptable<KEY_SIZE> for &[u8] {
/// Decrypts a slice of bytes using a provided password.
///
/// # Arguments
/// * `password`: The password to use for decryption.
///
/// # Returns
/// A `Result` containing the decrypted data as a vector of bytes, or an error string if decryption fails.
fn decrypt(&self, password: String) -> Result<Vec<u8>, EnclaveError> {
self.to_vec().decrypt(password)
}
/// Decrypts a slice of bytes using a provided key.
///
/// # Arguments
/// * `key`: The 32-byte cipher key used for decryption.
///
/// # Returns
/// A `Result` containing the decrypted data as a vector of bytes, or an error string if decryption fails.
fn decrypt_with_key(&self, key: [u8; KEY_SIZE]) -> Result<Vec<u8>, EnclaveError> {
self.to_vec().decrypt_with_key(key)
}
/// Decrypts a slice of bytes using a provided key.
///
/// # Arguments
/// * `key`: The 32-byte cipher key used for decryption.
///
/// # Returns
/// A `Result` containing the decrypted data as a vector of bytes, or an error string if decryption fails.
fn decrypt_with_metadata<M>(&self, key: [u8; KEY_SIZE]) -> Result<(Vec<u8>, M), EnclaveError>
where
M: TryFrom<Vec<u8>> + Into<Vec<u8>> + Clone,
{
self.to_vec().decrypt_with_metadata(key)
}
}
impl Encryptable<KEY_SIZE> for &[u8] {
/// Encrypts a slice of bytes using a provided password.
///
/// # Arguments
/// * `password`: The password to use for key derivation.
/// * `strategy`: The key derivation strategy to use.
///
/// # Returns
/// A `Vec<u8>` containing the encrypted data.
fn encrypt(&self, password: String, strategy: KeyDerivationStrategy) -> Vec<u8> {
self.to_vec().encrypt(password, strategy)
}
/// Encrypts a slice of bytes using a provided key.
///
/// # Arguments
/// * `key`: The 32-byte cipher key used for encryption.
///
/// # Returns
/// A `Vec<u8>` containing the encrypted data.
fn encrypt_with_key(&self, key: &Key<32, 16>) -> Vec<u8> {
self.to_vec().encrypt_with_key(key)
}
/// Encrypts a slice of bytes using a provided key.
///
/// # Arguments
/// * `key`: The 32-byte cipher key used for encryption.
///
/// # Returns
/// A `Vec<u8>` containing the encrypted data.
fn encrypt_with_raw_key(&self, key: [u8; KEY_SIZE]) -> Vec<u8> {
self.to_vec().encrypt_with_raw_key(key)
}
/// Encrypts a slice of bytes using a provided key and metadata.
///
/// # Arguments
/// * `key`: The 32-byte cipher key used for encryption.
/// * `metadata`: The metadata to be associated with the encrypted data.
///
/// # Returns
/// A `Vec<u8>` containing the encrypted data.
fn encrypt_with_metadata<M>(&self, key: [u8; KEY_SIZE], metadata: M) -> Vec<u8>
where
M: From<Vec<u8>> + Into<Vec<u8>> + Clone,
{
self.to_vec().encrypt_with_metadata(key, metadata)
}
}
impl Encryptable<KEY_SIZE> for String {
/// Encrypts a string using a provided password.
///
/// # Arguments
/// * `key`: The 32-byte cipher key used for encryption.
/// * `strategy`: The key derivation strategy to use.
///
/// # Returns
/// A `Vec<u8>` containing the encrypted data.
fn encrypt(&self, password: String, strategy: KeyDerivationStrategy) -> Vec<u8> {
self.as_bytes().to_vec().encrypt(password, strategy)
}
/// Encrypts a String using a provided key.
///
/// # Arguments
/// * `key`: The 32-byte cipher key used for encryption.
///
/// # Returns
/// A `Vec<u8>` containing the encrypted data.
fn encrypt_with_key(&self, key: &Key<32, 16>) -> Vec<u8> {
self.as_bytes().to_vec().encrypt_with_key(key)
}
/// Encrypts a String using a provided key.
///
/// # Arguments
/// * `key`: The 32-byte cipher key used for encryption.
///
/// # Returns
/// A `Vec<u8>` containing the encrypted data.
fn encrypt_with_raw_key(&self, key: [u8; KEY_SIZE]) -> Vec<u8> {
self.as_bytes().to_vec().encrypt_with_raw_key(key)
}
/// Encrypts a String using a provided key and metadata.
///
/// # Arguments
/// * `key`: The 32-byte cipher key used for encryption.
/// * `metadata`: The metadata to be associated with the encrypted data.
///
/// # Returns
/// A `Vec<u8>` containing the encrypted data.
fn encrypt_with_metadata<M>(&self, key: [u8; KEY_SIZE], metadata: M) -> Vec<u8>
where
M: From<Vec<u8>> + Into<Vec<u8>> + Clone,
{
self
.as_bytes()
.to_vec()
.encrypt_with_metadata(key, metadata)
}
}
impl Encryptable<KEY_SIZE> for &str {
/// Encrypts a &str using a provided password.
///
/// # Arguments
/// * `password`: The password to use for key derivation.
///
/// # Returns
/// A `Vec<u8>` containing the encrypted data.
fn encrypt(&self, password: String, strategy: KeyDerivationStrategy) -> Vec<u8> {
self.as_bytes().to_vec().encrypt(password, strategy)
}
/// Encrypts a string using a provided key.
///
/// # Arguments
/// * `key`: The 32-byte cipher key used for encryption.
///
/// # Returns
/// A `Vec<u8>` containing the encrypted data.
fn encrypt_with_key(&self, key: &Key<32, 16>) -> Vec<u8> {
self.as_bytes().to_vec().encrypt_with_key(key)
}
/// Encrypts a string using a provided key.
///
/// # Arguments
/// * `key`: The 32-byte cipher key used for encryption.
///
/// # Returns
/// A `Vec<u8>` containing the encrypted data.
fn encrypt_with_raw_key(&self, key: [u8; KEY_SIZE]) -> Vec<u8> {
self.as_bytes().to_vec().encrypt_with_raw_key(key)
}
/// Encrypts an &str using a provided key and metadata.
///
/// # Arguments
/// * `key`: The 32-byte cipher key used for encryption.
/// * `metadata`: The metadata to be associated with the encrypted data.
///
/// # Returns
/// A `Vec<u8>` containing the encrypted data.
fn encrypt_with_metadata<M>(&self, key: [u8; KEY_SIZE], metadata: M) -> Vec<u8>
where
M: From<Vec<u8>> + Into<Vec<u8>> + Clone,
{
self
.as_bytes()
.to_vec()
.encrypt_with_metadata(key, metadata)
}
}
#[cfg(test)]
mod tests {
use super::*;
mod from_plain_bytes {
use super::*;
#[test]
fn it_should_create_enclave() {
let key = [0u8; KEY_SIZE];
let bytes = [0u8, 1u8, 2u8, 3u8, 4u8].to_vec();
let safe = Enclave::from_plain_bytes(b"metadata".to_owned(), key, bytes);
assert!(safe.is_ok());
assert_eq!(safe.unwrap().metadata, b"metadata".to_owned());
}
}
mod decrypt {
use super::*;
#[test]
fn it_should_decrypt_enclave() {
let key = [0u8; KEY_SIZE];
let bytes = [0u8, 1u8, 2u8, 3u8, 4u8].to_vec();
let safe = Enclave::from_plain_bytes(b"metadata".to_vec(), key, bytes.clone()).unwrap();
let decrypted_bytes = safe.decrypt(key);
assert!(decrypted_bytes.is_ok());
assert_eq!(decrypted_bytes.unwrap(), bytes);
}
#[test]
fn it_should_fail_with_wrong_key() {
let key = [0u8; KEY_SIZE];
let bytes = [0u8, 1u8, 2u8, 3u8, 4u8].to_vec();
let safe = Enclave::from_plain_bytes(b"metadata".to_vec(), key, bytes.clone()).unwrap();
let wrong_key = [1u8; KEY_SIZE];
let decrypted_bytes = safe.decrypt(wrong_key);
assert!(!decrypted_bytes.is_ok());
}
#[test]
fn it_should_serialize_and_deserialize_to_bytes() {
let key = [0u8; KEY_SIZE];
let bytes = [0u8, 1u8, 2u8, 3u8, 4u8].to_vec();
let enclave = Enclave::from_plain_bytes([0_u8, 1_u8], key, bytes.clone()).unwrap();
let serialized: Vec<u8> = enclave.clone().into();
let deserialized = Enclave::try_from(serialized).unwrap();
assert_eq!(enclave, deserialized);
}
#[test]
fn vec_u8_should_be_encryptable_and_decryptable_with_password() {
let bytes = [0u8, 1u8, 2u8, 3u8, 4u8].to_vec();
let password = "my password".to_string();
// Using a low number of iterations here because tests are slow
let encrypted_bytes = bytes.encrypt(password.clone(), KeyDerivationStrategy::PBKDF2(10_000));
let decrypted_bytes = encrypted_bytes.decrypt(password);
assert!(decrypted_bytes.is_ok());
assert_eq!(decrypted_bytes.unwrap(), bytes);
}
#[test]
fn vec_u8_should_be_encryptable_and_decryptable_with_key() {
let bytes = [0u8, 1u8, 2u8, 3u8, 4u8].to_vec();
let key = [0u8; KEY_SIZE];
let encrypted_bytes = bytes.encrypt_with_raw_key(key);
let decrypted_bytes = encrypted_bytes.decrypt_with_key(key);
assert!(decrypted_bytes.is_ok());
assert_eq!(decrypted_bytes.unwrap(), bytes);
}
#[test]
fn vec_u8_should_be_encryptable_and_decryptable_with_metadata() {
let bytes = [0u8, 1u8, 2u8, 3u8, 4u8].to_vec();
let key = [0u8; KEY_SIZE];
let encrypted_bytes = bytes.encrypt_with_metadata(key, b"metadata".to_vec());
let decrypted_bytes = encrypted_bytes.decrypt_with_metadata::<Vec<u8>>(key);
assert!(decrypted_bytes.is_ok());
assert_eq!(decrypted_bytes.unwrap(), (bytes, b"metadata".to_vec()));
}
#[test]
fn strings_should_be_encryptable_and_decryptable_with_password() {
let string = "my string".to_string();
let password = "my password".to_string();
// Using a low number of iterations here because tests are slow
let encrypted_bytes = string.encrypt(password.clone(), KeyDerivationStrategy::PBKDF2(10_000));
let decrypted_bytes = encrypted_bytes.decrypt(password);
assert!(decrypted_bytes.is_ok());
assert_eq!(decrypted_bytes.unwrap(), string.as_bytes());
}
}
}