rustls/crypto/
hash.rs

1pub use crate::msgs::enums::HashAlgorithm;
2
3use alloc::boxed::Box;
4
5/// Describes a single cryptographic hash function.
6///
7/// This interface can do both one-shot and incremental hashing, using
8/// [`Hash::hash()`] and [`Hash::start()`] respectively.
9pub trait Hash: Send + Sync {
10    /// Start an incremental hash computation.
11    fn start(&self) -> Box<dyn Context>;
12
13    /// Return the output of this hash function with input `data`.
14    fn hash(&self, data: &[u8]) -> Output;
15
16    /// The length in bytes of this hash function's output.
17    fn output_len(&self) -> usize;
18
19    /// Which hash function this is, eg, `HashAlgorithm::SHA256`.
20    fn algorithm(&self) -> HashAlgorithm;
21}
22
23/// A hash output, stored as a value.
24pub struct Output {
25    buf: [u8; Self::MAX_LEN],
26    used: usize,
27}
28
29impl Output {
30    /// Build a `hash::Output` from a slice of no more than `Output::MAX_LEN` bytes.
31    pub fn new(bytes: &[u8]) -> Self {
32        let mut output = Self {
33            buf: [0u8; Self::MAX_LEN],
34            used: bytes.len(),
35        };
36        debug_assert!(bytes.len() <= Self::MAX_LEN);
37        output.buf[..bytes.len()].copy_from_slice(bytes);
38        output
39    }
40
41    /// Maximum supported hash output size: supports up to SHA512.
42    pub const MAX_LEN: usize = 64;
43}
44
45impl AsRef<[u8]> for Output {
46    fn as_ref(&self) -> &[u8] {
47        &self.buf[..self.used]
48    }
49}
50
51/// How to incrementally compute a hash.
52pub trait Context: Send + Sync {
53    /// Finish the computation, returning the resulting output.
54    ///
55    /// The computation remains valid, and more data can be added later with
56    /// [`Context::update()`].
57    ///
58    /// Compare with [`Context::finish()`] which consumes the computation
59    /// and prevents any further data being added.  This can be more efficient
60    /// because it avoids a hash context copy to apply Merkle-Damgård padding
61    /// (if required).
62    fn fork_finish(&self) -> Output;
63
64    /// Fork the computation, producing another context that has the
65    /// same prefix as this one.
66    fn fork(&self) -> Box<dyn Context>;
67
68    /// Terminate and finish the computation, returning the resulting output.
69    ///
70    /// Further data cannot be added after this, because the context is consumed.
71    /// Compare [`Context::fork_finish()`].
72    fn finish(self: Box<Self>) -> Output;
73
74    /// Add `data` to computation.
75    fn update(&mut self, data: &[u8]);
76}