summaryrefslogtreecommitdiffstats
path: root/openpgp/src/crypto/backend/openssl/hash.rs
blob: b4f6d81619b031a110141d47d0108085d3007d6d (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
104
use crate::crypto::hash::Digest;
use crate::types::HashAlgorithm;
use crate::Result;

use openssl::error::ErrorStack;
use openssl::hash::{Hasher, MessageDigest};
use openssl::nid::Nid;

#[derive(Clone)]
struct OpenSslDigest {
    digest_size: usize,
    algo: HashAlgorithm,
    hasher: Hasher,
    update_result: std::result::Result<(), ErrorStack>,
}

impl OpenSslDigest {
    fn new(algo: HashAlgorithm) -> Result<Self> {
        if let Some(md) = get_md(algo) {
            Ok(Self {
                digest_size: md.size(),
                algo,
                update_result: Ok(()),
                hasher: Hasher::new(md)?,
            })
        } else {
            Err(crate::Error::UnsupportedHashAlgorithm(algo).into())
        }
    }
}

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

    fn digest_size(&self) -> usize {
        self.digest_size
    }

    fn update(&mut self, data: &[u8]) {
        if self.update_result.is_ok() {
            self.update_result = self.hasher.update(data);
        }
    }

    fn digest(&mut self, digest: &mut [u8]) -> Result<()> {
        self.update_result.clone()?;
        let result = self.hasher.finish()?;
        digest.copy_from_slice(&result[..digest.len()]);
        Ok(())
    }
}

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

fn get_md(algo: HashAlgorithm) -> Option<MessageDigest> {
    use HashAlgorithm::*;
    let nid = match algo {
        MD5 => Nid::MD5,
        RipeMD => Nid::RIPEMD160,
        SHA1 => Nid::SHA1,
        SHA256 => Nid::SHA256,
        SHA384 => Nid::SHA384,
        SHA512 => Nid::SHA512,
        SHA224 => Nid::SHA224,
        HashAlgorithm::Private(_) |
        HashAlgorithm::Unknown(_) => return None,
    };
    MessageDigest::from_nid(nid)
}

impl HashAlgorithm {
    /// Whether Sequoia supports this algorithm.
    pub fn is_supported(self) -> bool {
        // Try to construct a digest.  This indirectly looks up
        // digest's Nid and tries to initialize OpenSSL hasher.  If
        // all of that succeeds the algorithm is supported by the
        // OpenSSL backend.
        OpenSslDigest::new(self).is_ok()
    }

    /// 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(OpenSslDigest::new(self)?))
    }
}