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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
#![allow(unused_doc_comment)]
extern crate base64;
extern crate byteorder;
extern crate crypto;
#[macro_use]
extern crate error_chain;
mod reader;
mod writer;
pub mod errors {
error_chain! {
foreign_links {
Utf8(::std::str::Utf8Error);
}
errors {
InvalidFormat {
description("invalid key format")
display("invalid key format")
}
UnsupportedKeytype(t: String) {
description("unsupported keytype")
display("unsupported keytype: {}", t)
}
UnsupportedCurve(t: String) {
description("unsupported curve")
display("unsupported curve: {}", t)
}
}
}
}
use errors::*;
use crypto::digest::Digest;
use crypto::sha2::Sha256;
use reader::Reader;
use writer::Writer;
use std::fmt;
const SSH_RSA: &'static str = "ssh-rsa";
const SSH_DSA: &'static str = "ssh-dss";
const SSH_ED25519: &'static str = "ssh-ed25519";
const SSH_ECDSA_256: &'static str = "ecdsa-sha2-nistp256";
const SSH_ECDSA_384: &'static str = "ecdsa-sha2-nistp384";
const SSH_ECDSA_521: &'static str = "ecdsa-sha2-nistp521";
const NISTP_256: &'static str = "nistp256";
const NISTP_384: &'static str = "nistp384";
const NISTP_521: &'static str = "nistp521";
#[derive(Clone, Debug)]
pub enum Curve {
Nistp256,
Nistp384,
Nistp521,
}
impl Curve {
fn get(curve: &str) -> Result<Self> {
Ok(match curve {
NISTP_256 => Curve::Nistp256,
NISTP_384 => Curve::Nistp384,
NISTP_521 => Curve::Nistp521,
_ => return Err(ErrorKind::UnsupportedCurve(curve.to_string()).into())
})
}
fn curvetype(&self) -> &'static str {
match *self {
Curve::Nistp256 => NISTP_256,
Curve::Nistp384 => NISTP_384,
Curve::Nistp521 => NISTP_521,
}
}
}
impl fmt::Display for Curve {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.curvetype())
}
}
#[derive(Clone, Debug)]
pub enum Data {
Rsa {
exponent: Vec<u8>,
modulus: Vec<u8>,
},
Dsa {
p: Vec<u8>,
q: Vec<u8>,
g: Vec<u8>,
pub_key: Vec<u8>,
},
Ed25519 {
key: Vec<u8>,
},
Ecdsa {
curve: Curve,
key: Vec<u8>,
},
}
#[derive(Clone, Debug)]
pub struct PublicKey {
data: Data,
comment: Option<String>,
}
impl fmt::Display for PublicKey {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.to_key_file())
}
}
impl PublicKey {
pub fn parse(key: &str) -> Result<Self> {
let mut parts = key.split_whitespace();
let keytype = parts.next().ok_or(ErrorKind::InvalidFormat)?;
let data = parts.next().ok_or(ErrorKind::InvalidFormat)?;
let comment = parts.next().and_then(|c| if c.is_empty() { None } else { Some(c.to_string()) });
let buf = base64::decode(data)
.chain_err(|| ErrorKind::InvalidFormat)?;
let mut reader = Reader::new(&buf);
let data_keytype = reader.read_string()?;
if keytype != data_keytype {
return Err(ErrorKind::InvalidFormat.into());
}
let data = match keytype {
SSH_RSA => {
let e = reader.read_mpint()?;
let n = reader.read_mpint()?;
Data::Rsa {
exponent: e.into(),
modulus: n.into(),
}
},
SSH_DSA => {
let p = reader.read_mpint()?;
let q = reader.read_mpint()?;
let g = reader.read_mpint()?;
let pub_key = reader.read_mpint()?;
Data::Dsa {
p: p.into(),
q: q.into(),
g: g.into(),
pub_key: pub_key.into(),
}
},
SSH_ED25519 => {
let key = reader.read_bytes()?;
Data::Ed25519 {
key: key.into(),
}
},
SSH_ECDSA_256 | SSH_ECDSA_384 | SSH_ECDSA_521 => {
let curve = reader.read_string()?;
let key = reader.read_bytes()?;
Data::Ecdsa {
curve: Curve::get(curve)?,
key: key.into(),
}
},
_ => return Err(ErrorKind::UnsupportedKeytype(keytype.into()).into()),
};
Ok(PublicKey {
data: data,
comment: comment,
})
}
pub fn from_rsa(e: Vec<u8>, n: Vec<u8>) -> Self {
PublicKey {
data: Data::Rsa {
exponent: e,
modulus: n,
},
comment: None,
}
}
pub fn from_dsa(p: Vec<u8>, q: Vec<u8>, g: Vec<u8>, pkey: Vec<u8>) -> Self {
PublicKey {
data: Data::Dsa {
p: p,
q: q,
g: g,
pub_key: pkey,
},
comment: None,
}
}
pub fn keytype(&self) -> &'static str {
match self.data {
Data::Rsa{..} => SSH_RSA,
Data::Dsa{..} => SSH_DSA,
Data::Ed25519{..} => SSH_ED25519,
Data::Ecdsa{ref curve,..} => match *curve {
Curve::Nistp256 => SSH_ECDSA_256,
Curve::Nistp384 => SSH_ECDSA_384,
Curve::Nistp521 => SSH_ECDSA_521,
},
}
}
pub fn data(&self) -> Vec<u8> {
let mut writer = Writer::new();
writer.write_string(self.keytype());
match self.data {
Data::Rsa{ref exponent, ref modulus} => {
writer.write_mpint(exponent.clone());
writer.write_mpint(modulus.clone());
}
Data::Dsa{ref p, ref q, ref g, ref pub_key} => {
writer.write_mpint(p.clone());
writer.write_mpint(q.clone());
writer.write_mpint(g.clone());
writer.write_mpint(pub_key.clone());
}
Data::Ed25519{ref key} => {
writer.write_bytes(key.clone());
}
Data::Ecdsa{ref curve, ref key} => {
writer.write_string(curve.curvetype());
writer.write_bytes(key.clone());
}
}
writer.to_vec()
}
pub fn set_comment(&mut self, comment: &str) {
self.comment = Some(comment.to_string());
}
pub fn to_key_file(&self) -> String {
format!("{} {} {}", self.keytype(), base64::encode(&self.data()), self.comment.clone().unwrap_or_default())
}
pub fn size(&self) -> usize {
match self.data {
Data::Rsa{ref modulus,..} => modulus.len()*8,
Data::Dsa{ref p,..} => p.len()*8,
Data::Ed25519{..} => 256,
Data::Ecdsa{ref curve,..} => match *curve {
Curve::Nistp256 => 256,
Curve::Nistp384 => 384,
Curve::Nistp521 => 521,
}
}
}
pub fn fingerprint(&self) -> String {
let data = self.data();
let mut hasher = Sha256::new();
hasher.input(&data);
let mut hashed: [u8; 32] = [0; 32];
hasher.result(&mut hashed);
let mut fingerprint = base64::encode(&hashed);
match fingerprint.find('=') {
Some(l) => { fingerprint.split_off(l); },
None => {},
}
format!("SHA256:{}", fingerprint)
}
pub fn to_fingerprint_string(&self) -> String {
let keytype = match self.data {
Data::Rsa{..} => "RSA",
Data::Dsa{..} => "DSA",
Data::Ed25519{..} => "ED25519",
Data::Ecdsa{..} => "ECDSA",
};
format!("{} {} {} ({})", self.size(), self.fingerprint(), self.comment.clone().unwrap_or("no comment".to_string()), keytype)
}
}
#[cfg(test)]
mod tests {
use super::*;
const TEST_RSA_KEY: &'static str = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCYH3vPUJThzriVlVKmKOg71EOVYm274oRa5KLWEoK0HmjMc9ru0j4ofouoeW/AVmRVujxfaIGR/8en/lUPkiv5DSeM6aXnDz5cExNptrAy/sMPLQhVALRrqQ+dkS9Ct/YA+A1Le5LPh4MJu79hCDLTwqSdKqDuUcYQzR0M7APslaDCR96zY+VUL4lKObUUd4wsP3opdTQ6G20qXEer14EPGr9N53S/u+JJGLoPlb1uPIH96oKY4t/SeLIRQsocdViRaiF/Aq7kPzWd/yCLVdXJSRt3CftboV4kLBHGteTS551J32MJoqjEi4Q/DucWYrQfx5H3qXVB+/G2HurKPIHL demos@siril";
const TEST_RSA_COMMENT_KEY: &'static str = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCYH3vPUJThzriVlVKmKOg71EOVYm274oRa5KLWEoK0HmjMc9ru0j4ofouoeW/AVmRVujxfaIGR/8en/lUPkiv5DSeM6aXnDz5cExNptrAy/sMPLQhVALRrqQ+dkS9Ct/YA+A1Le5LPh4MJu79hCDLTwqSdKqDuUcYQzR0M7APslaDCR96zY+VUL4lKObUUd4wsP3opdTQ6G20qXEer14EPGr9N53S/u+JJGLoPlb1uPIH96oKY4t/SeLIRQsocdViRaiF/Aq7kPzWd/yCLVdXJSRt3CftboV4kLBHGteTS551J32MJoqjEi4Q/DucWYrQfx5H3qXVB+/G2HurKPIHL test";
const TEST_DSA_KEY: &'static str = "ssh-dss AAAAB3NzaC1kc3MAAACBAIkd9CkqldM2St8f53rfJT7kPgiA8leZaN7hdZd48hYJyKzVLoPdBMaGFuOwGjv0Im3JWqWAewANe0xeLceQL0rSFbM/mZV+1gc1nm1WmtVw4KJIlLXl3gS7NYfQ9Ith4wFnZd/xhRz9Q+MBsA1DgXew1zz4dLYI46KmFivJ7XDzAAAAFQC8z4VIhI4HlHTvB7FdwAfqWsvcOwAAAIBEqPIkW3HHDTSEhUhhV2AlIPNwI/bqaCXy2zYQ6iTT3oUh+N4xlRaBSvW+h2NC97U8cxd7Y0dXIbQKPzwNzRX1KA1F9WAuNzrx9KkpCg2TpqXShhp+Sseb+l6uJjthIYM6/0dvr9cBDMeExabPPgBo3Eii2NLbFSqIe86qav8hZAAAAIBk5AetZrG8varnzv1khkKh6Xq/nX9r1UgIOCQos2XOi2ErjlB9swYCzReo1RT7dalITVi7K9BtvJxbutQEOvN7JjJnPJs+M3OqRMMF+anXPdCWUIBxZUwctbkAD5joEjGDrNXHQEw9XixZ9p3wudbISnPFgZhS1sbS9Rlw5QogKg== demos@siril";
const TEST_ED25519_KEY: &'static str = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhBr6++FQXB8kkgOMbdxBuyrHzuX5HkElswrN6DQoN/ demos@siril";
const TEST_ECDSA256_KEY: &'static str = "ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBIhfLQrww4DlhYzbSWXoX3ctOQ0jVosvfHfW+QWVotksbPzM2YgkIikTpoHUfZrYpJKWx7WYs5aqeLkdCDdk+jk= demos@siril";
#[test]
fn rsa_parse_to_string() {
let key = PublicKey::parse(TEST_RSA_KEY).unwrap();
let out = key.to_string();
assert_eq!(TEST_RSA_KEY, out);
}
#[test]
fn rsa_size() {
let key = PublicKey::parse(TEST_RSA_KEY).unwrap();
assert_eq!(2048, key.size());
}
#[test]
fn rsa_keytype() {
let key = PublicKey::parse(TEST_RSA_KEY).unwrap();
assert_eq!("ssh-rsa", key.keytype());
}
#[test]
fn rsa_fingerprint() {
let key = PublicKey::parse(TEST_RSA_KEY).unwrap();
assert_eq!("SHA256:YTw/JyJmeAAle1/7zuZkPP0C73BQ+6XrFEt2/Wy++2o", key.fingerprint());
}
#[test]
fn rsa_fingerprint_string() {
let key = PublicKey::parse(TEST_RSA_KEY).unwrap();
assert_eq!("2048 SHA256:YTw/JyJmeAAle1/7zuZkPP0C73BQ+6XrFEt2/Wy++2o demos@siril (RSA)", key.to_fingerprint_string());
}
#[test]
fn rsa_set_comment() {
let mut key = PublicKey::parse(TEST_RSA_KEY).unwrap();
key.set_comment("test");
let out = key.to_string();
assert_eq!(TEST_RSA_COMMENT_KEY, out);
}
#[test]
fn dsa_parse_to_string() {
let key = PublicKey::parse(TEST_DSA_KEY).unwrap();
let out = key.to_string();
assert_eq!(TEST_DSA_KEY, out);
}
#[test]
fn dsa_size() {
let key = PublicKey::parse(TEST_DSA_KEY).unwrap();
assert_eq!(1024, key.size());
}
#[test]
fn dsa_keytype() {
let key = PublicKey::parse(TEST_DSA_KEY).unwrap();
assert_eq!("ssh-dss", key.keytype());
}
#[test]
fn dsa_fingerprint() {
let key = PublicKey::parse(TEST_DSA_KEY).unwrap();
assert_eq!("SHA256:/Pyxrjot1Hs5PN2Dpg/4pK2wxxtP9Igc3sDTAWIEXT4", key.fingerprint());
}
#[test]
fn dsa_fingerprint_string() {
let key = PublicKey::parse(TEST_DSA_KEY).unwrap();
assert_eq!("1024 SHA256:/Pyxrjot1Hs5PN2Dpg/4pK2wxxtP9Igc3sDTAWIEXT4 demos@siril (DSA)", key.to_fingerprint_string());
}
#[test]
fn ed25519_parse_to_string() {
let key = PublicKey::parse(TEST_ED25519_KEY).unwrap();
let out = key.to_string();
assert_eq!(TEST_ED25519_KEY, out);
}
#[test]
fn ed25519_size() {
let key = PublicKey::parse(TEST_ED25519_KEY).unwrap();
assert_eq!(256, key.size());
}
#[test]
fn ed25519_keytype() {
let key = PublicKey::parse(TEST_ED25519_KEY).unwrap();
assert_eq!("ssh-ed25519", key.keytype());
}
#[test]
fn ed25519_fingerprint() {
let key = PublicKey::parse(TEST_ED25519_KEY).unwrap();
assert_eq!("SHA256:A/lHzXxsgbp11dcKKfSDyNQIdep7EQgZEoRYVDBfNdI", key.fingerprint());
}
#[test]
fn ed25519_fingerprint_string() {
let key = PublicKey::parse(TEST_ED25519_KEY).unwrap();
assert_eq!("256 SHA256:A/lHzXxsgbp11dcKKfSDyNQIdep7EQgZEoRYVDBfNdI demos@siril (ED25519)", key.to_fingerprint_string());
}
#[test]
fn ecdsa256_parse_to_string() {
let key = PublicKey::parse(TEST_ECDSA256_KEY).unwrap();
let out = key.to_string();
assert_eq!(TEST_ECDSA256_KEY, out);
}
#[test]
fn ecdsa256_size() {
let key = PublicKey::parse(TEST_ECDSA256_KEY).unwrap();
assert_eq!(256, key.size());
}
#[test]
fn ecdsa256_keytype() {
let key = PublicKey::parse(TEST_ECDSA256_KEY).unwrap();
assert_eq!("ecdsa-sha2-nistp256", key.keytype());
}
#[test]
fn ecdsa256_fingerprint() {
let key = PublicKey::parse(TEST_ECDSA256_KEY).unwrap();
assert_eq!("SHA256:BzS5YXMW/d2vFk8Oqh+nKmvKr8X/FTLBfJgDGLu5GAs", key.fingerprint());
}
#[test]
fn ecdsa256_fingerprint_string() {
let key = PublicKey::parse(TEST_ECDSA256_KEY).unwrap();
assert_eq!("256 SHA256:BzS5YXMW/d2vFk8Oqh+nKmvKr8X/FTLBfJgDGLu5GAs demos@siril (ECDSA)", key.to_fingerprint_string());
}
}