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
use std::fmt;
use Fingerprint;
use KeyID;
use Result;
impl fmt::Display for Fingerprint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.to_string())
}
}
impl fmt::Debug for Fingerprint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("Fingerprint")
.field(&self.to_string())
.finish()
}
}
impl Fingerprint {
pub fn from_bytes(raw: &[u8]) -> Fingerprint {
if raw.len() == 20 {
let mut fp : [u8; 20] = Default::default();
fp.copy_from_slice(raw);
Fingerprint::V4(fp)
} else {
Fingerprint::Invalid(raw.to_vec().into_boxed_slice())
}
}
pub fn from_hex(hex: &str) -> Result<Fingerprint> {
Ok(Fingerprint::from_bytes(&::conversions::from_hex(hex, true)?[..]))
}
pub fn as_slice(&self) -> &[u8] {
match self {
&Fingerprint::V4(ref fp) => fp,
&Fingerprint::Invalid(ref fp) => fp,
}
}
pub fn to_string(&self) -> String {
self.convert_to_string(true)
}
pub fn to_hex(&self) -> String {
self.convert_to_string(false)
}
fn convert_to_string(&self, pretty: bool) -> String {
let raw = match self {
&Fingerprint::V4(ref fp) => &fp[..],
&Fingerprint::Invalid(ref fp) => &fp[..],
};
let mut output = Vec::with_capacity(
raw.len() * 2
+ if pretty {
raw.len() / 2
+ raw.len() / 10
} else { 0 });
for (i, b) in raw.iter().enumerate() {
if pretty && i > 0 && i % 2 == 0 {
output.push(' ' as u8);
}
if pretty && i > 0 && i % 10 == 0 {
output.push(' ' as u8);
}
let top = b >> 4;
let bottom = b & 0xFu8;
if top < 10u8 {
output.push('0' as u8 + top)
} else {
output.push('A' as u8 + (top - 10u8))
}
if bottom < 10u8 {
output.push('0' as u8 + bottom)
} else {
output.push('A' as u8 + (bottom - 10u8))
}
}
String::from_utf8(output).unwrap()
}
pub fn to_keyid(&self) -> KeyID {
match self {
&Fingerprint::V4(ref fp) =>
KeyID::from_bytes(&fp[fp.len() - 8..]),
&Fingerprint::Invalid(ref fp) => {
if fp.len() < 8 {
KeyID::from_bytes(&[0; 8])
} else {
KeyID::from_bytes(&fp[fp.len() - 8..])
}
}
}
}
}