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
use std::{
    fmt::{self, Display, Formatter},
    str::FromStr,
};

use openssl::{hash::MessageDigest, x509::X509Ref};

use crate::Error;

/// Unknown hash function.
#[derive(Debug, Copy, Clone)]
pub struct UnknownHashFunction;

impl Display for UnknownHashFunction {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        f.write_str("unknown hash function")
    }
}

impl std::error::Error for UnknownHashFunction {}

/// Hash function.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum HashFunction {
    Md5,
    Sha1,
    Sha224,
    Sha256,
    Sha384,
    Sha512,
}

impl HashFunction {
    /// Get the OpenSSL message digest.
    pub(crate) fn into_message_digest(self) -> MessageDigest {
        match self {
            Self::Md5 => MessageDigest::md5(),
            Self::Sha1 => MessageDigest::sha1(),
            Self::Sha224 => MessageDigest::sha224(),
            Self::Sha256 => MessageDigest::sha256(),
            Self::Sha384 => MessageDigest::sha384(),
            Self::Sha512 => MessageDigest::sha512(),
        }
    }

    /// Get size of the resulting hash in bits.
    pub(crate) fn hash_size(self) -> usize {
        match self {
            Self::Md5 => 128,
            Self::Sha1 => 160,
            Self::Sha224 => 224,
            Self::Sha256 => 256,
            Self::Sha384 => 384,
            Self::Sha512 => 512,
        }
    }
}

impl Display for HashFunction {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        let s = match self {
            Self::Md5 => "md5",
            Self::Sha1 => "sha-1",
            Self::Sha224 => "sha-224",
            Self::Sha256 => "sha-256",
            Self::Sha384 => "sha-384",
            Self::Sha512 => "sha-512",
        };

        f.write_str(s)
    }
}

impl FromStr for HashFunction {
    type Err = UnknownHashFunction;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let res = match s {
            "md5" => Self::Md5,
            "sha-1" => Self::Sha1,
            "sha-224" => Self::Sha224,
            "sha-256" => Self::Sha256,
            "sha-384" => Self::Sha384,
            "sha-512" => Self::Sha512,
            _ => return Err(UnknownHashFunction),
        };

        Ok(res)
    }
}

/// Invalid fingerprint.
#[derive(Debug, Copy, Clone)]
pub enum InvalidFingerprint {
    UnknownHashFunction,
    InvalidData,
}

impl Display for InvalidFingerprint {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match self {
            Self::UnknownHashFunction => Display::fmt(&UnknownHashFunction, f),
            Self::InvalidData => f.write_str("invalid data"),
        }
    }
}

impl std::error::Error for InvalidFingerprint {}

impl From<UnknownHashFunction> for InvalidFingerprint {
    #[inline]
    fn from(_: UnknownHashFunction) -> Self {
        Self::UnknownHashFunction
    }
}

/// Certificate fingerprint.
///
/// The fingerprint can be formatted/parsed to/from an uppercase hex string
/// prefixed with the name of the hash function.
#[derive(Clone, Eq, PartialEq)]
pub struct CertificateFingerprint {
    hash_function: HashFunction,
    fingerprint: Vec<u8>,
}

impl CertificateFingerprint {
    /// Create fingerprint of a given certificate.
    #[inline]
    pub fn new(cert: &X509Ref, hash_function: HashFunction) -> Result<Self, Error> {
        let digest = cert.digest(hash_function.into_message_digest())?;

        let res = Self {
            hash_function,
            fingerprint: digest.to_vec(),
        };

        Ok(res)
    }

    /// Verify that this fingerprint matches a given certificate.
    #[inline]
    pub fn verify(&self, cert: &X509Ref) -> Result<bool, Error> {
        let other = Self::new(cert, self.hash_function)?;

        Ok(self == &other)
    }
}

impl Display for CertificateFingerprint {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        Display::fmt(&self.hash_function, f)?;

        let mut bytes = self.fingerprint.iter();

        if let Some(b) = bytes.next() {
            write!(f, " {:02X}", b)?;
        }

        for b in bytes {
            write!(f, ":{:02X}", b)?;
        }

        Ok(())
    }
}

impl FromStr for CertificateFingerprint {
    type Err = InvalidFingerprint;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let s = s.trim();

        if let Some(space) = s.find(' ') {
            let (hash_function, rest) = s.split_at(space);

            let digest = rest.trim();

            let hash_function = HashFunction::from_str(hash_function)?;

            let hash_size = hash_function.hash_size() >> 3;

            let mut fingerprint = Vec::with_capacity(hash_size);

            for byte in digest.split(':') {
                let byte =
                    u8::from_str_radix(byte, 16).map_err(|_| InvalidFingerprint::InvalidData)?;

                fingerprint.push(byte);
            }

            if fingerprint.len() != hash_size {
                return Err(InvalidFingerprint::InvalidData);
            }

            let res = Self {
                hash_function,
                fingerprint,
            };

            Ok(res)
        } else {
            Err(InvalidFingerprint::InvalidData)
        }
    }
}