Repository navigation
Expand file tree
/
Copy pathsecurity.rs
More file actions
270 lines (234 loc) · 7.81 KB
/
Copy pathsecurity.rs
File metadata and controls
270 lines (234 loc) · 7.81 KB
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
pub mod base64engine {
use base64::{ Engine, alphabet, engine::{ self, general_purpose } };
const CUSTOM_ENGINE: engine::GeneralPurpose = engine::GeneralPurpose::new(
&alphabet::URL_SAFE,
general_purpose::NO_PAD
);
pub fn base64_encode(input: &[u8]) -> String {
CUSTOM_ENGINE.encode(input)
}
pub fn base64_decode(input: &str) -> Vec<u8> {
CUSTOM_ENGINE.decode(input).unwrap()
}
}
pub mod aes {
use std::{ collections::HashMap, fs::File, io::{ Read, Write }, vec };
use aes_gcm::{
Aes256Gcm, // Or `Aes128Gcm`
Key,
Nonce,
aead::{ Aead, AeadCore, KeyInit, OsRng },
};
pub fn create_keys_dir() -> std::io::Result<()> {
if std::fs::DirBuilder::new().recursive(true).create("keys").is_err() {
return Err(
std::io::Error::new(
std::io::ErrorKind::Other,
"Failed to create the 'keys' directory."
)
);
}
Ok(())
}
pub fn generate_key() -> Key<Aes256Gcm> {
Aes256Gcm::generate_key(OsRng)
}
pub fn save_key(name: &str, key: Key<Aes256Gcm>) -> std::io::Result<()> {
let mut file = File::create(format!("keys/{name}"))?;
file.write_all(key.as_slice())?;
Ok(())
}
pub fn load_key(name: &str) -> std::io::Result<Key<Aes256Gcm>> {
let mut file = match File::open(format!("keys/{name}")) {
Ok(file) => file,
Err(_) => {
return Err(
std::io::Error::new(std::io::ErrorKind::NotFound, "Failed to open file.")
);
}
};
let mut buf = vec![];
match file.read_to_end(&mut buf) {
Ok(_) => {
if buf.is_empty() {
return Err(
std::io::Error::new(std::io::ErrorKind::InvalidData, "Key is empty.")
);
}
if buf.len() != 32 {
return Err(
std::io::Error::new(std::io::ErrorKind::InvalidData, "Key is not 32 bytes.")
);
}
}
Err(_) => {
return Err(std::io::Error::new(std::io::ErrorKind::Other, "Failed to read file."));
}
}
Ok(Key::<Aes256Gcm>::from_slice(buf.as_slice()).to_owned())
}
pub type KeyMap = HashMap<String, Key<Aes256Gcm>>;
pub fn load_all_keys() -> std::io::Result<HashMap<String, Key<Aes256Gcm>>> {
let mut keys = HashMap::new();
let entries = match std::fs::read_dir("keys") {
Ok(entries) => entries,
Err(_) => {
return Err(
std::io::Error::new(std::io::ErrorKind::NotFound, "Directory 'keys' missing.")
);
}
};
for entry in entries {
let entry = match entry {
Ok(entry) => entry,
Err(_) => {
continue;
}
};
let name = match entry.file_name().to_str() {
Some(name) => name.to_string(),
None => {
continue;
}
};
let key = match load_key(name.as_str()) {
Ok(key) => key,
Err(_) => {
continue;
}
};
keys.insert(name, key);
}
Ok(keys)
}
pub fn encrypt(data: &[u8], key: &Key<Aes256Gcm>) -> Vec<u8> {
let nonce = Aes256Gcm::generate_nonce(&mut OsRng); // 96-bits; unique per message
let cipher = Aes256Gcm::new(&key);
let ciphered_data = cipher.encrypt(&nonce, data).expect("Failed to encrypt data.");
[nonce.as_slice(), ciphered_data.as_slice()].concat()
}
pub fn decrypt(data: &[u8], key: &Key<Aes256Gcm>) -> Vec<u8> {
let (nonce, data) = data.split_at(12);
let nonce = Nonce::from_slice(nonce);
let cipher = Aes256Gcm::new(&key);
cipher
.decrypt(nonce, data)
.expect("Failed to decrypt data. Maybe the key doesn't match the name?")
}
}
#[cfg(test)]
pub mod tests {
use super::{ aes::*, base64engine::* };
#[test]
pub fn test_create_keys_dir() {
match create_keys_dir() {
Ok(_) =>
assert!(std::path::Path::new("keys").exists(), "Keys directory does not exist."),
Err(e) => {
panic!("Failed to create keys directory: {:?}", e);
}
};
}
#[test]
pub fn test_key_gen_encode_and_decode() {
let key = generate_key();
let keyb64 = base64_encode(key.as_slice());
let key2 = base64_decode(&keyb64);
assert_ne!(key.as_slice(), keyb64.as_bytes());
assert_eq!(key.as_slice(), key2)
}
#[test]
pub fn test_encrypt_and_decrypt() {
let key = generate_key();
let data = b"Hello, World!";
let encrypted_data = encrypt(data, &key);
let decrypted_data = decrypt(encrypted_data.as_slice(), &key);
assert_ne!(data, encrypted_data.as_slice());
assert_eq!(data, decrypted_data.as_slice());
}
#[test]
pub fn test_save_key() {
match save_key("cluster_key_testrunner", generate_key()) {
Ok(_) => {}
Err(e) => {
println!("Failed to save key: {:?}", e);
}
};
}
#[test]
pub fn test_save_key_and_load_key() {
let key = generate_key();
match save_key("cluster_key_testrunner2", key) {
Ok(_) => {}
Err(e) => {
panic!("Failed to save key: {:?}", e);
}
}
let key2 = match load_key("cluster_key_testrunner2") {
Ok(key) => key,
Err(e) => {
panic!("Failed to load key: {:?}", e);
}
};
assert_eq!(key.as_slice(), key2.as_slice());
}
#[test]
pub fn test_load_key() {
if let Err(e) = create_keys_dir() {
panic!("Failed to create keys directory: {:?}", e);
}
match save_key("cluster_key_testrunner3", generate_key()) {
Ok(_) => {}
Err(e) => {
println!("Failed to save key: {:?}", e);
}
};
let key = match load_key("cluster_key_testrunner3") {
Ok(key) => key,
Err(e) => {
panic!("Failed to load key: {:?}", e);
}
};
assert_eq!(key.as_slice().len(), 32);
}
#[test]
pub fn test_load_all_keys() {
if let Err(e) = create_keys_dir() {
panic!("Failed to create keys directory: {:?}", e);
}
match save_key("cluster_key_testrunner4", generate_key()) {
Ok(_) => {}
Err(e) => {
println!("Failed to save key: {:?}", e);
}
};
match save_key("cluster_key_testrunner5", generate_key()) {
Ok(_) => {}
Err(e) => {
println!("Failed to save key: {:?}", e);
}
};
let keys = match load_all_keys() {
Ok(keys) => keys,
Err(e) => {
panic!("Failed to load all keys: {:?}", e);
}
};
assert!(keys.len() >= 2);
}
#[test]
pub fn test_path() {
println!("Path: {:?}", workspace_dir());
}
fn workspace_dir() -> std::path::PathBuf {
let output = std::process::Command
::new(env!("CARGO"))
.arg("locate-project")
.arg("--workspace")
.arg("--message-format=plain")
.output()
.unwrap().stdout;
let cargo_path = std::path::Path::new(std::str::from_utf8(&output).unwrap().trim());
cargo_path.parent().unwrap().to_path_buf()
}
}