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
/// A generic trait that exposes the information that is needed for a hash function to be
/// used in `sign` and `verify.`.
pub trait Hash {
    /// Returns the length in bytes of a digest.
    fn size(&self) -> usize;

    /// Returns the ASN1 DER prefix for the the hash function.
    fn asn1_prefix(&self) -> Vec<u8>;
}

/// A list of provided hashes, implementing `Hash`.
#[derive(Debug, Clone, Copy)]
pub enum Hashes {
    MD5,
    SHA1,
    SHA224,
    SHA256,
    SHA384,
    SHA512,
    MD5SHA1,
    RIPEMD160,
}

impl Hash for Hashes {
    fn size(&self) -> usize {
        match *self {
            Hashes::MD5 => 16,
            Hashes::SHA1 => 20,
            Hashes::SHA224 => 28,
            Hashes::SHA256 => 32,
            Hashes::SHA384 => 48,
            Hashes::SHA512 => 64,
            Hashes::MD5SHA1 => 36,
            Hashes::RIPEMD160 => 20,
        }
    }

    fn asn1_prefix(&self) -> Vec<u8> {
        match *self {
            Hashes::MD5 => vec![
                0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05,
                0x05, 0x00, 0x04, 0x10,
            ],
            Hashes::SHA1 => vec![
                0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04,
                0x14,
            ],
            Hashes::SHA224 => vec![
                0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02,
                0x04, 0x05, 0x00, 0x04, 0x1c,
            ],
            Hashes::SHA256 => vec![
                0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02,
                0x01, 0x05, 0x00, 0x04, 0x20,
            ],
            Hashes::SHA384 => vec![
                0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02,
                0x02, 0x05, 0x00, 0x04, 0x30,
            ],

            Hashes::SHA512 => vec![
                0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02,
                0x03, 0x05, 0x00, 0x04, 0x40,
            ],

            // A special TLS case which doesn't use an ASN1 prefix
            Hashes::MD5SHA1 => Vec::new(),
            Hashes::RIPEMD160 => vec![
                0x30, 0x20, 0x30, 0x08, 0x06, 0x06, 0x28, 0xcf, 0x06, 0x03, 0x00, 0x31, 0x04, 0x14,
            ],
        }
    }
}