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
use arrayref::array_ref;
use rsa::pkcs1::{FromRsaPrivateKey, FromRsaPublicKey};
use std::fmt;
use subtle::{Choice, ConstantTimeEq};
use zeroize::Zeroize;
pub const RSA_ID_LEN: usize = 20;
#[derive(Clone, Copy, Hash, Zeroize, Ord, PartialOrd)]
#[allow(clippy::derive_hash_xor_eq)]
pub struct RsaIdentity {
id: [u8; RSA_ID_LEN],
}
impl ConstantTimeEq for RsaIdentity {
fn ct_eq(&self, other: &Self) -> Choice {
self.id.ct_eq(&other.id)
}
}
impl PartialEq<RsaIdentity> for RsaIdentity {
fn eq(&self, rhs: &RsaIdentity) -> bool {
self.ct_eq(rhs).unwrap_u8() == 1
}
}
impl Eq for RsaIdentity {}
impl fmt::Display for RsaIdentity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "${}", hex::encode(&self.id[..]))
}
}
impl fmt::Debug for RsaIdentity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "RsaIdentity {{ {} }}", self)
}
}
impl serde::Serialize for RsaIdentity {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
if serializer.is_human_readable() {
serializer.serialize_str(&hex::encode(&self.id[..]))
} else {
serializer.serialize_bytes(&self.id[..])
}
}
}
impl<'de> serde::Deserialize<'de> for RsaIdentity {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
if deserializer.is_human_readable() {
struct RsaIdentityVisitor;
impl<'de> serde::de::Visitor<'de> for RsaIdentityVisitor {
type Value = RsaIdentity;
fn expecting(&self, fmt: &mut std::fmt::Formatter<'_>) -> fmt::Result {
fmt.write_str("hex-encoded RSA identity")
}
fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
RsaIdentity::from_hex(s)
.ok_or_else(|| E::custom("wrong encoding for RSA identity"))
}
}
deserializer.deserialize_str(RsaIdentityVisitor)
} else {
struct RsaIdentityVisitor;
impl<'de> serde::de::Visitor<'de> for RsaIdentityVisitor {
type Value = RsaIdentity;
fn expecting(&self, fmt: &mut std::fmt::Formatter<'_>) -> fmt::Result {
fmt.write_str("RSA identity")
}
fn visit_bytes<E>(self, bytes: &[u8]) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
RsaIdentity::from_bytes(bytes)
.ok_or_else(|| E::custom("wrong length for RSA identity"))
}
}
deserializer.deserialize_bytes(RsaIdentityVisitor)
}
}
}
impl RsaIdentity {
pub fn as_bytes(&self) -> &[u8] {
&self.id[..]
}
pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
if bytes.len() == RSA_ID_LEN {
Some(RsaIdentity {
id: *array_ref![bytes, 0, RSA_ID_LEN],
})
} else {
None
}
}
pub fn from_hex(s: &str) -> Option<Self> {
let mut array = [0_u8; 20];
match hex::decode_to_slice(s, &mut array) {
Err(_) => None,
Ok(()) => Some(RsaIdentity::from(array)),
}
}
}
impl From<[u8; 20]> for RsaIdentity {
fn from(id: [u8; 20]) -> RsaIdentity {
RsaIdentity { id }
}
}
#[derive(Clone, Debug)]
pub struct PublicKey(rsa::RsaPublicKey);
pub struct PrivateKey(rsa::RsaPrivateKey);
impl PrivateKey {
pub fn to_public_key(&self) -> PublicKey {
PublicKey(self.0.to_public_key())
}
pub fn from_der(der: &[u8]) -> Option<Self> {
Some(PrivateKey(rsa::RsaPrivateKey::from_pkcs1_der(der).ok()?))
}
}
impl PublicKey {
pub fn exponent_is(&self, e: u32) -> bool {
use rsa::PublicKeyParts;
*self.0.e() == rsa::BigUint::new(vec![e])
}
pub fn bits(&self) -> usize {
use rsa::PublicKeyParts;
self.0.n().bits()
}
pub fn verify(&self, hashed: &[u8], sig: &[u8]) -> Result<(), signature::Error> {
use rsa::PublicKey;
let padding = rsa::PaddingScheme::new_pkcs1v15_sign(None);
self.0
.verify(padding, hashed, sig)
.map_err(|_| signature::Error::new())
}
pub fn from_der(der: &[u8]) -> Option<Self> {
Some(PublicKey(rsa::RsaPublicKey::from_pkcs1_der(der).ok()?))
}
pub fn to_der(&self) -> Vec<u8> {
use rsa::BigUint;
use rsa::PublicKeyParts;
use simple_asn1::{ASN1Block, BigInt};
fn to_asn1_int(x: &BigUint) -> ASN1Block {
let mut bytes = vec![0];
bytes.extend(x.to_bytes_be());
let bigint = BigInt::from_signed_bytes_be(&bytes);
ASN1Block::Integer(0, bigint)
}
let asn1 = ASN1Block::Sequence(0, vec![to_asn1_int(self.0.n()), to_asn1_int(self.0.e())]);
simple_asn1::to_der(&asn1).expect("RSA key not encodable as DER")
}
pub fn to_rsa_identity(&self) -> RsaIdentity {
use crate::d::Sha1;
use digest::Digest;
let id = Sha1::digest(&self.to_der()).into();
RsaIdentity { id }
}
}
pub struct ValidatableRsaSignature {
key: PublicKey,
sig: Vec<u8>,
expected_hash: Vec<u8>,
}
impl ValidatableRsaSignature {
pub fn new(key: &PublicKey, sig: &[u8], expected_hash: &[u8]) -> Self {
ValidatableRsaSignature {
key: key.clone(),
sig: sig.into(),
expected_hash: expected_hash.into(),
}
}
}
impl super::ValidatableSignature for ValidatableRsaSignature {
fn is_valid(&self) -> bool {
self.key
.verify(&self.expected_hash[..], &self.sig[..])
.is_ok()
}
}