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
extern crate base64;
extern crate serde;
extern crate serde_json;
extern crate snafu;
#[macro_use]
extern crate serde_derive;
extern crate ssb_crypto;
use std::fs::File;
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use serde::Serialize;
use serde_json::error::Error as JsonError;
use snafu::{OptionExt as _, ResultExt as _, Snafu};
use ssb_crypto::{PublicKey, SecretKey};
#[derive(Debug, Deserialize)]
struct SecretFile {
public: String,
private: String,
}
pub fn load_keys_from_path<P: AsRef<Path>>(path: P) -> Result<(PublicKey, SecretKey), Error> {
let mut f = File::open(&path).with_context(|| FileRead {
path: path.as_ref().to_path_buf(),
})?;
let mut buf = [0u8; 1024];
f.read(&mut buf).with_context(|| FileRead {
path: path.as_ref().to_path_buf(),
})?;
let sec_str = std::str::from_utf8(&buf).context(Utf8)?;
keys_from_str(sec_str)
}
#[derive(Debug, Serialize)]
struct SecretFileFull {
curve: &'static str,
public: String,
private: String,
id: String,
}
pub fn keys_from_str(s: &str) -> Result<(PublicKey, SecretKey), Error> {
let sec_str = s
.lines()
.filter(|s| !s.starts_with('#'))
.collect::<Vec<&str>>()
.concat();
let sec = serde_json::from_str::<SecretFile>(&sec_str).context(Json)?;
let pbytes = decode_b64_key(&sec.public).context(DecodePublic)?;
let sbytes = decode_b64_key(&sec.private).context(DecodeSecret)?;
let p = PublicKey::from_slice(&pbytes).context(CreatePublic)?;
let s = SecretKey::from_slice(&sbytes).context(CreateSecret)?;
Ok((p, s))
}
fn decode_b64_key(s: &str) -> Result<Vec<u8>, base64::DecodeError> {
base64::decode_config(s.trim_end_matches(".ed25519"), base64::STANDARD)
}
fn encode_key(bytes: &[u8]) -> String {
let mut out = base64::encode_config(bytes, base64::STANDARD);
out.push_str(".ed25519");
out
}
pub fn new_keyfile_string(pk: &PublicKey, sk: &SecretKey) -> String {
let mut msg = Vec::with_capacity(727);
let id = {
let mut p = encode_key(&pk.0);
p.insert(0, '@');
p
};
let kf = SecretFileFull {
curve: "ed25519",
public: encode_key(&pk.0),
private: encode_key(&sk.0),
id: id,
};
msg.extend_from_slice(PRE_COMMENT.as_bytes());
let formatter = serde_json::ser::PrettyFormatter::with_indent(b"");
let mut ser = serde_json::Serializer::with_formatter(&mut msg, formatter);
kf.serialize(&mut ser).unwrap();
msg.extend_from_slice(POST_COMMENT.as_bytes());
msg.extend_from_slice(kf.id.as_bytes());
String::from_utf8(msg).unwrap()
}
#[derive(Debug, Snafu)]
pub enum Error {
#[snafu(display("Failed to read secret file at path: {} with error: {}", path.display(), source))]
FileRead { path: PathBuf, source: io::Error },
#[snafu(display("Secret file isn't valid utf8: {}", source))]
Utf8 { source: std::str::Utf8Error },
#[snafu(display("Failed to deserialize secret file: {}", source))]
Json { source: JsonError },
#[snafu(display("Failed to decode public key: {}", source))]
DecodePublic { source: base64::DecodeError },
#[snafu(display("Failed to decode public key: {}", source))]
DecodeSecret { source: base64::DecodeError },
#[snafu(display("Failed to decode public key."))]
CreatePublic {},
#[snafu(display("Failed to decode public key."))]
CreateSecret {},
}
const PRE_COMMENT: &'static str = "# this is your SECRET name.
# this name gives you magical powers.
# with it you can mark your messages so that your friends can verify
# that they really did come from you.
#
# if any one learns this name, they can use it to destroy your identity
# NEVER show this to anyone!!!
";
const POST_COMMENT: &'static str = "
# WARNING! It's vital that you DO NOT edit OR share your secret name
# instead, share your public name
# your public name: ";
#[cfg(test)]
mod tests {
use super::*;
fn test_data_file(name: &str) -> PathBuf {
let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
d.push("test-data");
d.push(name);
d
}
#[test]
fn read_js_file() {
let (pk, sk) = load_keys_from_path(test_data_file("secret")).unwrap();
assert_eq!(
pk.0,
[
31u8, 106, 151, 121, 46, 108, 56, 165, 42, 104, 99, 69, 129, 18, 122, 169, 30, 60,
250, 80, 30, 63, 64, 189, 150, 175, 72, 86, 84, 12, 162, 215
]
);
assert_eq!(pk, sk.public_key());
let newkf = new_keyfile_string(&pk, &sk);
assert_eq!(
newkf,
std::fs::read_to_string(test_data_file("secret")).unwrap()
);
}
}