summaryrefslogtreecommitdiffstats
path: root/third_party/rust/hawk/src/crypto/ring.rs
blob: 6721b9352c9d8e8d3f58c3a191204ba7fa15fc38 (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
use super::{CryptoError, Cryptographer, Hasher, HmacKey};
use crate::DigestAlgorithm;
use ring::{digest, hmac};
use std::convert::{TryFrom, TryInto};

impl From<ring::error::Unspecified> for CryptoError {
    // Ring's errors are entirely opaque
    fn from(_: ring::error::Unspecified) -> Self {
        CryptoError::Other(anyhow::Error::msg("Unspecified ring error"))
    }
}

impl From<std::convert::Infallible> for CryptoError {
    fn from(_: std::convert::Infallible) -> Self {
        unreachable!()
    }
}

pub struct RingCryptographer;

struct RingHmacKey(hmac::Key);

impl HmacKey for RingHmacKey {
    fn sign(&self, data: &[u8]) -> Result<Vec<u8>, CryptoError> {
        let digest = hmac::sign(&self.0, data);
        let mut mac = vec![0; self.0.algorithm().digest_algorithm().output_len];
        mac.copy_from_slice(digest.as_ref());
        Ok(mac)
    }
}
// This is always `Some` until `finish` is called.
struct RingHasher(Option<digest::Context>);

impl Hasher for RingHasher {
    fn update(&mut self, data: &[u8]) -> Result<(), CryptoError> {
        self.0
            .as_mut()
            .expect("update called after `finish`")
            .update(data);
        Ok(())
    }

    fn finish(&mut self) -> Result<Vec<u8>, CryptoError> {
        let digest = self.0.take().expect("`finish` called twice").finish();
        let bytes: &[u8] = digest.as_ref();
        Ok(bytes.to_owned())
    }
}

impl Cryptographer for RingCryptographer {
    fn rand_bytes(&self, output: &mut [u8]) -> Result<(), CryptoError> {
        use ring::rand::SecureRandom;
        let rnd = ring::rand::SystemRandom::new();
        rnd.fill(output)?;
        Ok(())
    }

    fn new_key(
        &self,
        algorithm: DigestAlgorithm,
        key: &[u8],
    ) -> Result<Box<dyn HmacKey>, CryptoError> {
        let k = hmac::Key::new(algorithm.try_into()?, key);
        Ok(Box::new(RingHmacKey(k)))
    }

    fn constant_time_compare(&self, a: &[u8], b: &[u8]) -> bool {
        ring::constant_time::verify_slices_are_equal(a, b).is_ok()
    }

    fn new_hasher(&self, algorithm: DigestAlgorithm) -> Result<Box<dyn Hasher>, CryptoError> {
        let ctx = digest::Context::new(algorithm.try_into()?);
        Ok(Box::new(RingHasher(Some(ctx))))
    }
}

impl TryFrom<DigestAlgorithm> for &'static digest::Algorithm {
    type Error = CryptoError;
    fn try_from(algorithm: DigestAlgorithm) -> Result<Self, CryptoError> {
        match algorithm {
            DigestAlgorithm::Sha256 => Ok(&digest::SHA256),
            DigestAlgorithm::Sha384 => Ok(&digest::SHA384),
            DigestAlgorithm::Sha512 => Ok(&digest::SHA512),
            algo => Err(CryptoError::UnsupportedDigest(algo)),
        }
    }
}

impl TryFrom<DigestAlgorithm> for hmac::Algorithm {
    type Error = CryptoError;
    fn try_from(algorithm: DigestAlgorithm) -> Result<Self, CryptoError> {
        match algorithm {
            DigestAlgorithm::Sha256 => Ok(hmac::HMAC_SHA256),
            DigestAlgorithm::Sha384 => Ok(hmac::HMAC_SHA384),
            DigestAlgorithm::Sha512 => Ok(hmac::HMAC_SHA512),
            algo => Err(CryptoError::UnsupportedDigest(algo)),
        }
    }
}