summaryrefslogtreecommitdiffstats
path: root/openpgp/src/crypto/backend/botan/hash.rs
blob: 0e02b5ddd3f444713101f3599b57f869275872df (plain)
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
use std::io;

use crate::crypto::hash::Digest;
use crate::{Error, Result};
use crate::types::HashAlgorithm;

#[derive(Clone)]
struct Hash(HashAlgorithm, botan::HashFunction);

impl Digest for Hash {
    fn algo(&self) -> HashAlgorithm {
        self.0
    }

    fn digest_size(&self) -> usize {
        self.1.output_length().expect("infallible")
    }

    fn update(&mut self, data: &[u8]) {
        self.1.update(data).expect("infallible");
    }

    fn digest(&mut self, digest: &mut [u8]) -> Result<()> {
        let d = self.1.finish().expect("infallible");
        let l = d.len().min(digest.len());
        digest[..l].copy_from_slice(&d[..l]);
        Ok(())
    }
}

impl io::Write for Hash {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.update(buf);
        Ok(buf.len())
    }
    fn flush(&mut self) -> io::Result<()> {
        // Do nothing.
        Ok(())
    }
}

impl HashAlgorithm {
    /// Whether Sequoia supports this algorithm.
    pub fn is_supported(self) -> bool {
        match self {
            HashAlgorithm::SHA1 => true,
            HashAlgorithm::SHA224 => true,
            HashAlgorithm::SHA256 => true,
            HashAlgorithm::SHA384 => true,
            HashAlgorithm::SHA512 => true,
            HashAlgorithm::RipeMD => true,
            HashAlgorithm::MD5 => true,
            HashAlgorithm::Private(_) => false,
            HashAlgorithm::Unknown(_) => false,
        }
    }

    /// Creates a new hash context for this algorithm.
    ///
    /// # Errors
    ///
    /// Fails with `Error::UnsupportedHashAlgorithm` if Sequoia does
    /// not support this algorithm. See
    /// [`HashAlgorithm::is_supported`].
    ///
    ///   [`HashAlgorithm::is_supported`]: HashAlgorithm::is_supported()
    pub(crate) fn new_hasher(self) -> Result<Box<dyn Digest>> {
        Ok(Box::new(Hash(
            self,
            botan::HashFunction::new(self.botan_name()?)
                .map_err(|_| Error::UnsupportedHashAlgorithm(self))?)))
    }
}

impl HashAlgorithm {
    /// Returns the name of the algorithm for use with Botan's
    /// constructor.
    pub(crate) fn botan_name(self) -> Result<&'static str> {
        match self {
            HashAlgorithm::SHA1 => Ok("SHA-1"),
            HashAlgorithm::SHA224 => Ok("SHA-224"),
            HashAlgorithm::SHA256 => Ok("SHA-256"),
            HashAlgorithm::SHA384 => Ok("SHA-384"),
            HashAlgorithm::SHA512 => Ok("SHA-512"),
            HashAlgorithm::MD5 => Ok("MD5"),
            HashAlgorithm::RipeMD => Ok("RIPEMD-160"),
            HashAlgorithm::Private(_) | HashAlgorithm::Unknown(_) =>
                Err(Error::UnsupportedHashAlgorithm(self).into()),
        }
    }
}

#[cfg(tests)]
mod tests {
    use super::*;

    #[test]
    fn is_supported() {
        for h in (0..256).iter().map(HashAlgorithm::from) {
            assert_eq!(h.is_supported(), h.context().is_ok());
        }
    }
}