/
crypto.rs
570 lines (501 loc) · 18.1 KB
/
crypto.rs
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
//! Cryptographic structures and functions.
use data_encoding::HEXLOWER;
use ring;
use ring::digest::{self, SHA256};
use ring::rand::SystemRandom;
use ring::signature::{RSAKeyPair, RSASigningState, Ed25519KeyPair, ED25519,
RSA_PSS_2048_8192_SHA256, RSA_PSS_2048_8192_SHA512, RSA_PSS_SHA256,
RSA_PSS_SHA512};
use serde::de::{Deserialize, Deserializer, Error as DeserializeError};
use serde::ser::{Serialize, Serializer, SerializeTupleStruct, Error as SerializeError};
use std::collections::HashMap;
use std::fmt::{self, Debug, Display};
use std::str::FromStr;
use std::sync::Arc;
use untrusted::Input;
use Result;
use error::Error;
use rsa;
use shims;
static HASH_ALG_PREFS: &'static [HashAlgorithm] = &[HashAlgorithm::Sha512, HashAlgorithm::Sha256];
/// Given a map of hash algorithms and their values, get the prefered algorithm and the hash
/// calculated by it. Returns an `Err` if there is no match.
///
/// ```
/// use std::collections::HashMap;
/// use tuf::crypto::{hash_preference, HashValue, HashAlgorithm};
///
/// let mut map = HashMap::new();
/// assert!(hash_preference(&map).is_err());
///
/// let _ = map.insert(HashAlgorithm::Sha512, HashValue::from_hex("abcd").unwrap());
/// assert_eq!(hash_preference(&map).unwrap().0, &HashAlgorithm::Sha512);
///
/// let _ = map.insert(HashAlgorithm::Sha256, HashValue::from_hex("0123").unwrap());
/// assert_eq!(hash_preference(&map).unwrap().0, &HashAlgorithm::Sha512);
/// ```
pub fn hash_preference<'a>(
hashes: &'a HashMap<HashAlgorithm, HashValue>,
) -> Result<(&'static HashAlgorithm, &'a HashValue)> {
for alg in HASH_ALG_PREFS {
match hashes.get(alg) {
Some(v) => return Ok((alg, v)),
None => continue,
}
}
Err(Error::NoSupportedHashAlgorithm)
}
/// Calculate the given key's ID.
///
/// A `KeyId` is calculated as `sha256(public_key_bytes)`. The TUF spec says that it should be
/// `sha256(cjson(encoded(public_key_bytes)))`, but this is meaningless once the spec moves away
/// from using only JSON as the data interchange format.
pub fn calculate_key_id(public_key: &PublicKeyValue) -> KeyId {
let mut context = digest::Context::new(&SHA256);
context.update(&public_key.0);
KeyId(context.finish().as_ref().to_vec())
}
/// Wrapper type for public key's ID.
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct KeyId(Vec<u8>);
impl KeyId {
/// Parse a key ID from a hex-lower string.
pub fn from_string(string: &str) -> Result<Self> {
if string.len() != 64 {
return Err(Error::IllegalArgument(
"Hex key ID must be 64 characters long".into(),
));
}
Ok(KeyId(HEXLOWER.decode(string.as_bytes())?))
}
}
impl Debug for KeyId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "KeyId {{ \"{}\" }}", HEXLOWER.encode(&self.0))
}
}
impl Serialize for KeyId {
fn serialize<S>(&self, ser: S) -> ::std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut s = ser.serialize_tuple_struct("KeyId", 1)?;
s.serialize_field(&HEXLOWER.encode(&self.0))?;
s.end()
}
}
impl<'de> Deserialize<'de> for KeyId {
fn deserialize<D: Deserializer<'de>>(de: D) -> ::std::result::Result<Self, D::Error> {
let string: String = Deserialize::deserialize(de)?;
KeyId::from_string(&string).map_err(|e| DeserializeError::custom(format!("{:?}", e)))
}
}
/// Cryptographic signature schemes.
#[derive(Debug, PartialEq)]
pub enum SignatureScheme {
/// [Ed25519](https://ed25519.cr.yp.to/)
Ed25519,
/// [RSASSA-PSS](https://tools.ietf.org/html/rfc5756) calculated over SHA256
RsaSsaPssSha256,
/// [RSASSA-PSS](https://tools.ietf.org/html/rfc5756) calculated over SHA512
RsaSsaPssSha512,
}
impl ToString for SignatureScheme {
fn to_string(&self) -> String {
match self {
&SignatureScheme::Ed25519 => "ed25519",
&SignatureScheme::RsaSsaPssSha256 => "rsassa-pss-sha256",
&SignatureScheme::RsaSsaPssSha512 => "rsassa-pss-sha512",
}.to_string()
}
}
impl FromStr for SignatureScheme {
type Err = Error;
fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> {
match s {
"ed25519" => Ok(SignatureScheme::Ed25519),
"rsassa-pss-sha256" => Ok(SignatureScheme::RsaSsaPssSha256),
"rsassa-pss-sha512" => Ok(SignatureScheme::RsaSsaPssSha512),
typ => Err(Error::Encoding(typ.into())),
}
}
}
impl Serialize for SignatureScheme {
fn serialize<S>(&self, ser: S) -> ::std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
ser.serialize_str(&self.to_string())
}
}
impl<'de> Deserialize<'de> for SignatureScheme {
fn deserialize<D: Deserializer<'de>>(de: D) -> ::std::result::Result<Self, D::Error> {
let string: String = Deserialize::deserialize(de)?;
Ok(string.parse().unwrap())
}
}
/// Wrapper type for the value of a cryptographic signature.
#[derive(PartialEq)]
pub struct SignatureValue(Vec<u8>);
impl SignatureValue {
/// Create a new `SignatureValue` from the given bytes.
pub fn new(bytes: Vec<u8>) -> Self {
SignatureValue(bytes)
}
/// Create a new `SignatureValue` from the given hex-lower string.
pub fn from_string(string: &str) -> Result<Self> {
Ok(SignatureValue(HEXLOWER.decode(string.as_bytes())?))
}
}
impl Debug for SignatureValue {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "SignatureValue {{ \"{}\" }}", HEXLOWER.encode(&self.0))
}
}
impl Serialize for SignatureValue {
fn serialize<S>(&self, ser: S) -> ::std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut s = ser.serialize_tuple_struct("SignatureValue", 1)?;
s.serialize_field(&HEXLOWER.encode(&self.0))?;
s.end()
}
}
impl<'de> Deserialize<'de> for SignatureValue {
fn deserialize<D: Deserializer<'de>>(de: D) -> ::std::result::Result<Self, D::Error> {
let string: String = Deserialize::deserialize(de)?;
SignatureValue::from_string(&string).map_err(|e| {
DeserializeError::custom(format!("Signature value was not valid hex lower: {:?}", e))
})
}
}
/// Types of public keys.
#[derive(Clone, PartialEq, Debug)]
pub enum KeyType {
/// [Ed25519](https://ed25519.cr.yp.to/)
Ed25519,
/// [RSA](https://en.wikipedia.org/wiki/RSA_%28cryptosystem%29)
Rsa,
}
impl FromStr for KeyType {
type Err = Error;
fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> {
match s {
"ed25519" => Ok(KeyType::Ed25519),
"rsa" => Ok(KeyType::Rsa),
typ => Err(Error::Encoding(typ.into())),
}
}
}
impl ToString for KeyType {
fn to_string(&self) -> String {
match self {
&KeyType::Ed25519 => "ed25519",
&KeyType::Rsa => "rsa",
}.to_string()
}
}
impl Serialize for KeyType {
fn serialize<S>(&self, ser: S) -> ::std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
ser.serialize_str(&self.to_string())
}
}
impl<'de> Deserialize<'de> for KeyType {
fn deserialize<D: Deserializer<'de>>(de: D) -> ::std::result::Result<Self, D::Error> {
let string: String = Deserialize::deserialize(de)?;
Ok(string.parse().unwrap())
}
}
enum PrivateKeyType {
Ed25519(Ed25519KeyPair),
Rsa(Arc<RSAKeyPair>),
}
impl Debug for PrivateKeyType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let s = match self {
&PrivateKeyType::Ed25519(_) => "ed25519",
&PrivateKeyType::Rsa(_) => "rsa",
};
write!(f, "PrivateKeyType {{ \"{}\" }}", s)
}
}
/// A structure containing information about a public key.
pub struct PrivateKey {
private: PrivateKeyType,
}
impl PrivateKey {
/// Create an Ed25519 private key from PKCS#8v2 DER bytes.
pub fn ed25519_from_pkcs8(der_key: &[u8]) -> Result<Self> {
let key = Ed25519KeyPair::from_pkcs8(Input::from(der_key)).map_err(
|_| {
Error::Encoding("Could not parse key as PKCS#8v2".into())
},
)?;
Ok(PrivateKey { private: PrivateKeyType::Ed25519(key) })
}
/// Create an RSA private key from PKCS#8v2 DER bytes.
pub fn rsa_from_pkcs8(der_key: &[u8]) -> Result<Self> {
let key = RSAKeyPair::from_pkcs8(Input::from(der_key)).map_err(|_| {
Error::Encoding("Could not parse key as PKCS#8v2".into())
})?;
Ok(PrivateKey { private: PrivateKeyType::Rsa(Arc::new(key)) })
}
/// Sign a message with the given scheme.
pub fn sign(&self, msg: &[u8], scheme: &SignatureScheme) -> Result<SignatureValue> {
match (&self.private, scheme) {
(&PrivateKeyType::Rsa(ref rsa), &SignatureScheme::RsaSsaPssSha256) => {
let mut signing_state = RSASigningState::new(rsa.clone()).map_err(|_| {
Error::Opaque("Could not initialize RSA signing state.".into())
})?;
let rng = SystemRandom::new();
let mut buf = vec![0; signing_state.key_pair().public_modulus_len()];
signing_state
.sign(&RSA_PSS_SHA256, &rng, msg, &mut buf)
.map_err(|_| Error::Opaque("Failed to sign message.".into()))?;
Ok(SignatureValue(buf))
}
(&PrivateKeyType::Rsa(ref rsa), &SignatureScheme::RsaSsaPssSha512) => {
let mut signing_state = RSASigningState::new(rsa.clone()).map_err(|_| {
Error::Opaque("Could not initialize RSA signing state.".into())
})?;
let rng = SystemRandom::new();
let mut buf = vec![0; signing_state.key_pair().public_modulus_len()];
signing_state
.sign(&RSA_PSS_SHA512, &rng, msg, &mut buf)
.map_err(|_| Error::Opaque("Failed to sign message.".into()))?;
Ok(SignatureValue(buf))
}
(&PrivateKeyType::Ed25519(ref ed), &SignatureScheme::Ed25519) => {
Ok(SignatureValue(ed.sign(msg).as_ref().into()))
}
(k, s) => Err(Error::IllegalArgument(
format!("Key {:?} can't be used with scheme {:?}", k, s),
)),
}
}
}
/// A structure containing information about a public key.
#[derive(Clone, Debug, PartialEq)]
pub struct PublicKey {
typ: KeyType,
format: KeyFormat,
key_id: KeyId,
value: PublicKeyValue,
}
impl PublicKey {
/// Create a `PublicKey` from an Ed25519 `PublicKeyValue`.
pub fn from_ed25519(value: PublicKeyValue) -> Result<Self> {
if value.value().len() != 32 {
return Err(Error::Encoding(
"Ed25519 public key was not 32 bytes long".into(),
));
}
Ok(PublicKey {
typ: KeyType::Ed25519,
format: KeyFormat::HexLower,
key_id: calculate_key_id(&value),
value: value,
})
}
/// Create a `PublicKey` from an RSA `PublicKeyValue`, either SPKI or PKCS#1.
pub fn from_rsa(value: PublicKeyValue, format: KeyFormat) -> Result<Self> {
// TODO check n > 2048 bits (but this is ok because `ring` doesn't support less)
let key_id = calculate_key_id(&value);
let pkcs1_value = match format {
KeyFormat::Pkcs1 => {
let bytes = rsa::from_pkcs1(value.value()).ok_or_else(|| {
Error::IllegalArgument(
"Key claimed to be PKCS1 but could not be parsed.".into(),
)
})?;
PublicKeyValue(bytes)
}
KeyFormat::Spki => {
let bytes = rsa::from_spki(value.value()).ok_or_else(|| {
Error::IllegalArgument("Key claimed to be SPKI but could not be parsed.".into())
})?;
PublicKeyValue(bytes)
}
x => {
return Err(Error::IllegalArgument(
format!("RSA keys in format {:?} not supported.", x),
))
}
};
Ok(PublicKey {
typ: KeyType::Rsa,
format: format,
key_id: key_id,
value: pkcs1_value,
})
}
/// An immutable reference to the key's type.
pub fn typ(&self) -> &KeyType {
&self.typ
}
/// An immutable reference to the key's format.
pub fn format(&self) -> &KeyFormat {
&self.format
}
/// An immutable reference to the key's ID.
pub fn key_id(&self) -> &KeyId {
&self.key_id
}
/// An immutable reference to the key's public value.
pub fn value(&self) -> &PublicKeyValue {
&self.value
}
/// Use this key and the given signature scheme to verify the message again a signature.
pub fn verify(&self, scheme: &SignatureScheme, msg: &[u8], sig: &SignatureValue) -> Result<()> {
let alg: &ring::signature::VerificationAlgorithm = match scheme {
&SignatureScheme::Ed25519 => &ED25519,
&SignatureScheme::RsaSsaPssSha256 => &RSA_PSS_2048_8192_SHA256,
&SignatureScheme::RsaSsaPssSha512 => &RSA_PSS_2048_8192_SHA512,
};
ring::signature::verify(
alg,
Input::from(&self.value.0),
Input::from(msg),
Input::from(&sig.0),
).map_err(|_: ring::error::Unspecified| Error::BadSignature)
}
}
impl Serialize for PublicKey {
fn serialize<S>(&self, ser: S) -> ::std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
shims::PublicKey::from(self)
.map_err(|e| SerializeError::custom(format!("{:?}", e)))?
.serialize(ser)
}
}
impl<'de> Deserialize<'de> for PublicKey {
fn deserialize<D: Deserializer<'de>>(de: D) -> ::std::result::Result<Self, D::Error> {
let intermediate: shims::PublicKey = Deserialize::deserialize(de)?;
intermediate.try_into().map_err(|e| {
DeserializeError::custom(format!("{:?}", e))
})
}
}
/// Wrapper type for a decoded public key.
#[derive(Clone, Debug, PartialEq)]
pub struct PublicKeyValue(Vec<u8>);
impl PublicKeyValue {
/// Create a new `PublicKeyValue` from the given bytes.
pub fn new(bytes: Vec<u8>) -> Self {
PublicKeyValue(bytes)
}
/// An immutable reference to the public key's bytes.
pub fn value(&self) -> &[u8] {
&self.0
}
}
/// Possible encoding/decoding formats for a public key.
#[derive(Clone, Debug, PartialEq)]
pub enum KeyFormat {
/// The key should be read/written as hex-lower bytes.
HexLower,
/// The key should be read/written as PKCS#1 PEM.
Pkcs1,
/// The key should be read/written as SPKI PEM.
Spki,
}
/// A structure that contains a `Signature` and associated data for verifying it.
#[derive(Debug, Serialize, Deserialize)]
pub struct Signature {
key_id: KeyId,
scheme: SignatureScheme,
signature: SignatureValue,
}
impl Signature {
/// An immutable reference to the `KeyId` that produced the signature.
pub fn key_id(&self) -> &KeyId {
&self.key_id
}
/// An immutable reference to the `SignatureScheme` used to create this signature.
pub fn scheme(&self) -> &SignatureScheme {
&self.scheme
}
/// An immutable reference to the `SignatureValue`.
pub fn signature(&self) -> &SignatureValue {
&self.signature
}
}
/// The available hash algorithms.
#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)]
pub enum HashAlgorithm {
/// SHA256 as describe in [RFC-6234](https://tools.ietf.org/html/rfc6234)
#[serde(rename = "sha256")]
Sha256,
/// SHA512 as describe in [RFC-6234](https://tools.ietf.org/html/rfc6234)
#[serde(rename = "sha512")]
Sha512,
}
/// Wrapper for the value of a hash digest.
#[derive(Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct HashValue(Vec<u8>);
impl HashValue {
/// Parse a hex-lower string and return a `HashValue`.
///
/// ```
/// use tuf::crypto::HashValue;
/// assert_eq!(HashValue::from_hex("abcd").unwrap().value(), &[0xab, 0xcd]);
/// ```
pub fn from_hex(s: &str) -> Result<Self> {
Ok(HashValue(HEXLOWER.decode(s.as_bytes())?))
}
/// Create a new `HashValue` from the given digest bytes.
pub fn new(bytes: Vec<u8>) -> Self {
HashValue(bytes)
}
/// An immutable reference to the bytes of the hash value.
pub fn value(&self) -> &[u8] {
&self.0
}
}
impl Debug for HashValue {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "HashValue {{ \"{}\" }}", HEXLOWER.encode(&self.0))
}
}
impl Display for HashValue {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", HEXLOWER.encode(&self.0))
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn rsa_2048_ead_pkcs8_and_sign() {
let der = include_bytes!("../tests/rsa/rsa-2048-private-key.pk8");
let key = PrivateKey::rsa_from_pkcs8(der.as_ref()).unwrap();
let msg = b"test";
let _ = key.sign(msg, &SignatureScheme::RsaSsaPssSha256).unwrap();
let _ = key.sign(msg, &SignatureScheme::RsaSsaPssSha512).unwrap();
assert!(key.sign(msg, &SignatureScheme::Ed25519).is_err());
}
#[test]
fn rsa_4096_read_pkcs8_and_sign() {
let der = include_bytes!("../tests/rsa/rsa-4096-private-key.pk8");
let key = PrivateKey::rsa_from_pkcs8(der.as_ref()).unwrap();
let msg = b"test";
let _ = key.sign(msg, &SignatureScheme::RsaSsaPssSha256).unwrap();
let _ = key.sign(msg, &SignatureScheme::RsaSsaPssSha512).unwrap();
assert!(key.sign(msg, &SignatureScheme::Ed25519).is_err());
}
#[test]
fn ed25519_read_pkcs8_and_sign() {
let der = include_bytes!("../tests/ed25519/ed25519-1.pk8");
let key = PrivateKey::ed25519_from_pkcs8(der.as_ref()).unwrap();
let msg = b"test";
let _ = key.sign(msg, &SignatureScheme::Ed25519).unwrap();
assert!(key.sign(msg, &SignatureScheme::RsaSsaPssSha256).is_err());
assert!(key.sign(msg, &SignatureScheme::RsaSsaPssSha512).is_err());
}
}