Repository navigation
Expand file tree
/
Copy pathlib.rs
More file actions
174 lines (149 loc) · 4.54 KB
/
Copy pathlib.rs
File metadata and controls
174 lines (149 loc) · 4.54 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
extern crate base16;
#[cfg(test)]
extern crate quickcheck;
#[cfg(test)]
#[macro_use(quickcheck)]
extern crate quickcheck_macros;
use std::path::Path;
use std::fs::File;
use std::io::Write;
use cryptoxide::chacha20poly1305::ChaCha20Poly1305;
// FIXME no longer a keypair...
#[derive(Debug, PartialEq)]
pub struct Keypair {
key: [u8; 16],
}
#[derive(Debug)]
pub enum Error {
InvalidHex(base16::DecodeError),
InvalidKeyLength(usize),
InvalidMessage,
IO(std::io::Error),
Getrandom(getrandom::Error),
}
impl std::error::Error for Error {
}
impl std::fmt::Display for Error {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
// FIXME do better
write!(fmt, "{:?}", self)
}
}
impl From<base16::DecodeError> for Error {
fn from(e: base16::DecodeError) -> Error {
Error::InvalidHex(e)
}
}
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Error {
Error::IO(e)
}
}
impl From<getrandom::Error> for Error {
fn from(e: getrandom::Error) -> Error {
Error::Getrandom(e)
}
}
impl Keypair {
pub fn generate() -> Result<Keypair, Error> {
let mut key = [0; 16];
getrandom::getrandom(&mut key)?;
Ok(Keypair { key })
}
pub fn encode(&self) -> String {
base16::encode_lower(&self.key)
}
pub fn decode<T: AsRef<[u8]>>(hex: T) -> Result<Keypair, Error> {
let bytes = base16::decode(&hex)?;
let mut key: [u8; 16] = [0; 16];
if bytes.len() == 16 {
for i in 0..16 {
key[i] = bytes[i];
}
Ok(Keypair { key })
} else {
Err(Error::InvalidKeyLength(bytes.len()))
}
}
pub fn encode_file<P: AsRef<Path>>(&self, path: P) -> Result<(), std::io::Error> {
let mut file = File::create(path)?;
file.write_all(self.encode().as_bytes())?;
Ok(())
}
#[cfg(test)]
pub fn decode_file<P: AsRef<Path>>(path: P) -> Result<Keypair, Error> {
use std::io::Read;
let mut file = File::open(path)?;
let mut contents = vec![];
file.read_to_end(&mut contents)?;
Keypair::decode(&contents)
}
pub fn encrypt<T: AsRef<[u8]>>(&self, msg: T) -> Result<String, Error> {
let msg: &[u8] = msg.as_ref();
let mut nonce: [u8; 8] = [0; 8];
getrandom::getrandom(&mut nonce)?;
let mut key = ChaCha20Poly1305::new(&self.key, &nonce, &[]);
let mut tag = [0; 16];
let mut output: Vec<u8> = Vec::new();
output.resize(msg.len(), 0);
key.encrypt(msg, &mut output, &mut tag);
Ok(format!(
"{}{}{}",
base16::encode_lower(&nonce),
base16::encode_lower(&tag),
base16::encode_lower(&output),
))
}
pub fn decrypt<T: AsRef<[u8]>>(&self, hex: T) -> Result<Vec<u8>, Error> {
let noncetagcipher = base16::decode(&hex)?;
let nonce = &noncetagcipher[0..8];
let tag = &noncetagcipher[8..24];
let cipher = &noncetagcipher[24..];
let mut output: Vec<u8> = Vec::new();
output.resize(cipher.len(), 0);
let mut key = ChaCha20Poly1305::new(&self.key, nonce, &[]);
if key.decrypt(&cipher, &mut output, &tag) {
Ok(output)
} else {
Err(Error::InvalidMessage)
}
}
}
#[cfg(test)]
mod test {
extern crate tempfile;
use tempfile::tempdir;
use super::*;
#[test]
fn test_encode_decode_memory() {
let keypair = Keypair::generate().unwrap();
assert_eq!(keypair, Keypair::decode(&keypair.encode()).unwrap());
}
#[test]
fn test_encode_decode_files() {
let keypair = Keypair::generate().unwrap();
let dir = tempdir().unwrap();
let file = dir.path().join("keypair");
keypair.encode_file(&file).unwrap();
assert_eq!(keypair, Keypair::decode_file(&file).unwrap());
}
#[test]
fn test_fails_invalid_hex() {
Keypair::decode("this is not hex").unwrap_err();
}
#[test]
fn test_fails_invalid_signature() {
Keypair::decode("deadbeef1234").unwrap_err();
}
#[test]
fn test_fails_nonexistent_file() {
let dir = tempdir().unwrap();
let file = dir.path().join("does-not-exist");
Keypair::decode_file(file).unwrap_err();
}
#[quickcheck]
fn prop_encrypt_decrypt(secret: String) {
let keypair = Keypair::generate().unwrap();
assert_eq!(secret.as_bytes()[..], keypair.decrypt(keypair.encrypt(&secret).unwrap()).unwrap()[..])
}
}