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
use aes_gcm_siv::{
aead::{generic_array::GenericArray, rand_core::RngCore, Aead, OsRng},
Aes256GcmSiv, KeyInit, Nonce,
};
use anyhow::{anyhow, Context, Result};
use argon2::Config;
use log::{info, trace};
use serde_derive::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct PrecryptorFile {
data: Vec<u8>,
nonce: [u8; 12],
salt: [u8; 32],
}
pub fn encrypt(data: &[u8], password: &[u8]) -> Result<Vec<u8>> {
trace!("Generating salt");
let mut salt = [0u8; 32];
OsRng.fill_bytes(&mut salt);
let config = Config {
hash_length: 32,
..Default::default()
};
trace!("Generating key");
let password = argon2::hash_raw(password, &salt, &config)
.with_context(|| "Failed to generate key from password")?;
let key = GenericArray::from_slice(&password);
let cipher = Aes256GcmSiv::new(key);
trace!("Generating nonce");
let mut nonce_rand = [0u8; 12];
OsRng.fill_bytes(&mut nonce_rand);
let nonce = Nonce::from_slice(&nonce_rand);
info!("Encrypting");
let ciphertext = match cipher.encrypt(nonce, data.as_ref()) {
Ok(ciphertext) => ciphertext,
Err(_) => return Err(anyhow!("Failed to encrypt data -> invalid password")),
};
let file = PrecryptorFile {
data: ciphertext,
nonce: nonce_rand,
salt,
};
trace!("Encoding");
let encoded: Vec<u8> = bincode::serialize(&file).with_context(|| "Failed to decode data")?;
Ok(encoded)
}
pub fn decrypt(data: &[u8], password: &[u8]) -> Result<Vec<u8>> {
trace!("Decoding");
let decoded: PrecryptorFile =
bincode::deserialize(data).with_context(|| "Failed to decode data")?;
let config = Config {
hash_length: 32,
..Default::default()
};
trace!("Generating key");
let password = argon2::hash_raw(password, &decoded.salt, &config)
.with_context(|| "Failed to generate key from password")?;
let key = GenericArray::from_slice(&password);
let cipher = Aes256GcmSiv::new(key);
let nonce = Nonce::from_slice(&decoded.nonce);
info!("Decrypting");
let text = match cipher.decrypt(nonce, decoded.data.as_ref()) {
Ok(ciphertext) => ciphertext,
Err(_) => return Err(anyhow!("Failed to encrypt data -> invalid password")),
};
Ok(text)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let encrypted_data =
encrypt(b"example text", b"example passowrd").expect("Failed to encrypt");
let data = decrypt(&encrypted_data, b"example passowrd").expect("Failed to decrypt");
assert_eq!(data, b"example text");
}
}