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
pub use sodiumoxide::crypto::sign::ed25519::*;
use sodiumoxide;
use std;
use std::fs::OpenOptions;
use std::fs;
use std::os::unix::fs::OpenOptionsExt;
use std::io::Write;
use std::io::Read;
use std::io::Seek;
use std::io::SeekFrom;
use std::path::Path;
use std::fmt::Display;
fn to_utf8_hex<'a>(bytes: &[u8]) -> Vec<u8> {
let strings: Vec<String> = bytes.into_iter()
.map(|b| format!("{:02X}", b))
.collect();
let mut ret = Vec::new();
ret.extend_from_slice(strings.join(" ").as_bytes());
ret
}
pub fn key_gen_to_file<P: AsRef<Path> + Display + Clone>(file_path: P) where String: std::convert::From<P> {
let option = OpenOptions::new()
.write(true)
.truncate(true)
.create(true)
.mode(0o600)
.open(file_path.clone());
let mut file = match option {
Ok(f) => f,
Err(e) => panic!("Opening file '{}' failed with error: {}", file_path, e),
};
sodiumoxide::init();
let (pk, sk) = gen_keypair();
let _ = file.write(b"PK: ").unwrap();
let _ = file.write(&to_utf8_hex(&pk[..])).unwrap();
let _ = file.write(b"\nSK: ").unwrap();
let _ = file.write(&to_utf8_hex(&sk[..])).unwrap();
let _ = file.write(b"\n").unwrap();
let pub_option = OpenOptions::new()
.write(true)
.truncate(true)
.create(true)
.mode(0o600)
.open(String::from(file_path.clone()) + ".pub");
let mut pub_file = match pub_option {
Ok(f) => f,
Err(e) => panic!("Opening file '{}' failed with error: {}", file_path, e),
};
let _ = pub_file.write(b"PK: ").unwrap();
let _ = pub_file.write(&to_utf8_hex(&pk[..])).unwrap();
let _ = pub_file.write(b"\n").unwrap();
}
fn hex_char_to_num(c: char) -> u8 {
match c {
'0' => 0,
'1' => 1,
'2' => 2,
'3' => 3,
'4' => 4,
'5' => 5,
'6' => 6,
'7' => 7,
'8' => 8,
'9' => 9,
'A' => 10,
'B' => 11,
'C' => 12,
'D' => 13,
'E' => 14,
'F' => 15,
_ => panic!("{} is not a hexadecimal digit", c),
}
}
fn hex_to_byte(hex: Vec<char>) -> u8 {
assert_eq!(hex.len(), 2);
hex_char_to_num(hex[1]) | (hex_char_to_num(hex[0]) << 4)
}
fn get_key_from_file(mut file: fs::File, prefix: &str) -> Option<(fs::File, Vec<u8>)> {
let prefix_expected = String::from(prefix) + ": ";
let mut prefix_read_bytes: [u8; 4] = [0; 4];
match file.read(&mut prefix_read_bytes) {
Ok(_) => (),
Err(_) => return None,
};
if prefix_read_bytes != prefix_expected.as_bytes() {
if prefix_read_bytes != [10, 0, 0, 0] {
panic!("The prefix read (as bytes) was {:?}, we expected {:?} ('{}'). Is the file malformed?", prefix_read_bytes, prefix_expected.as_bytes(), prefix_expected);
} else {
return None;
}
}
let mut key_hex_vec = Vec::new();
match file.read_to_end(&mut key_hex_vec) {
Ok(_) => (),
Err(e) => panic!("Error reading file: {}", e),
};
if prefix == "PK" {
key_hex_vec.truncate(64 + 31);
} else {
key_hex_vec.truncate(128 + 63);
}
let key_hex: Vec<char> = String::from_utf8(key_hex_vec).unwrap().chars().collect();
let key: Vec<u8> = key_hex.split(|c| *c == ' ')
.map(|x| x.to_vec())
.map(|x| hex_to_byte(x))
.collect();
Some((file, key))
}
fn open_or_panic<P: AsRef<Path> + Display + Clone>(path: P) -> fs::File {
match fs::File::open(path.clone()) {
Ok(f) => f,
Err(e) => panic!("Error opening file '{}': {}", path, e),
}
}
pub fn get_keypair<P1: AsRef<Path> + Display + Clone>(my_keypair_path: P1) -> (PublicKey, SecretKey) {
let my_keypair_file = open_or_panic(my_keypair_path);
let (mut my_keypair_file, pk_bytes) = get_key_from_file(my_keypair_file, "PK").unwrap();
my_keypair_file.seek(SeekFrom::Start(4+64+31+1)).unwrap();
let (_, sk_bytes) = get_key_from_file(my_keypair_file, "SK").unwrap();
let my_pk = PublicKey::from_slice(&pk_bytes).unwrap();
let my_sk = SecretKey::from_slice(&sk_bytes).unwrap();
(my_pk, my_sk)
}
pub fn get_pubkey<P1: AsRef<Path> + Display + Clone>(their_pk_path: P1) -> PublicKey {
let pk_file = open_or_panic(their_pk_path);
let result = get_key_from_file(pk_file, "PK");
let (_, pk_bytes) = result.unwrap();
let their_pk = PublicKey::from_slice(&pk_bytes).unwrap();
their_pk
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs::remove_file;
#[test]
fn key_files() {
let test_file_path = "key_files_test_keyfile_deleteme";
let test_file_path_pub = String::from(test_file_path) + ".pub";
key_gen_to_file(test_file_path);
let _ = get_keypair(test_file_path);
let _ = get_pubkey(&test_file_path_pub);
remove_file(test_file_path).unwrap();
remove_file(test_file_path_pub).unwrap();
}
}