Skip to main content
This is unreleased documentation for the main (development) branch of crypto-glue.

digest/
lib.rs

1//! This crate provides traits which describe functionality of cryptographic hash
2//! functions and Message Authentication algorithms.
3//!
4//! Traits in this repository are organized into the following levels:
5//!
6//! - **High-level convenience traits**: [`Digest`], [`DynDigest`], [`Mac`].
7//!   Wrappers around lower-level traits for most common use-cases. Users should
8//!   usually prefer using these traits.
9//! - **Mid-level traits**: [`Update`], [`FixedOutput`], [`FixedOutputReset`], [`ExtendableOutput`],
10//!   [`ExtendableOutputReset`], [`XofReader`], [`Reset`], [`KeyInit`], and [`InnerInit`].
11//!   These traits atomically describe available functionality of an algorithm.
12//! - **Marker traits**: [`HashMarker`], [`MacMarker`]. Used to distinguish
13//!   different algorithm classes.
14//! - **Low-level traits** defined in the [`block_api`] module. These traits
15//!   operate at a block-level and do not contain any built-in buffering.
16//!   They are intended to be implemented by low-level algorithm providers only.
17//!   Usually they should not be used in application-level code.
18//!
19//! Additionally hash functions implement traits from the standard library:
20//! [`Default`] and [`Clone`].
21//!
22//! This crate does not provide any implementations of the `io::Read/Write` traits,
23//! see the [`digest-io`] crate for `std::io`-compatibility wrappers.
24//!
25//! [`digest-io`]: https://docs.rs/digest-io
26
27#![no_std]
28#![cfg_attr(docsrs, feature(doc_cfg))]
29#![forbid(unsafe_code)]
30#![doc(
31    html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg",
32    html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg"
33)]
34#![warn(missing_docs, rust_2018_idioms, missing_debug_implementations)]
35
36#[cfg(feature = "alloc")]
37#[macro_use]
38extern crate alloc;
39
40#[cfg(feature = "rand_core")]
41pub use common::rand_core;
42
43#[cfg(feature = "zeroize")]
44pub use zeroize;
45
46#[cfg(feature = "alloc")]
47use alloc::boxed::Box;
48
49#[cfg(feature = "dev")]
50pub mod dev;
51
52#[cfg(feature = "block-api")]
53pub mod block_api;
54mod buffer_macros;
55mod digest;
56#[cfg(feature = "mac")]
57mod mac;
58mod xof_fixed;
59
60#[cfg(feature = "block-api")]
61pub use block_buffer;
62pub use common;
63#[cfg(feature = "oid")]
64pub use const_oid;
65
66#[cfg(feature = "const-oid")]
67pub use crate::digest::DynDigestWithOid;
68pub use crate::digest::{Digest, DynDigest, HashMarker};
69#[cfg(feature = "mac")]
70pub use common::{InnerInit, InvalidLength, Key, KeyInit};
71pub use common::{Output, OutputSizeUser, Reset, array, typenum, typenum::consts};
72#[cfg(feature = "mac")]
73pub use mac::{CtOutput, Mac, MacError, MacMarker};
74pub use xof_fixed::XofFixedWrapper;
75
76use common::typenum::Unsigned;
77use core::fmt;
78
79/// Types which consume data with byte granularity.
80pub trait Update {
81    /// Update state using the provided data.
82    fn update(&mut self, data: &[u8]);
83
84    /// Digest input data in a chained manner.
85    #[must_use]
86    fn chain(mut self, data: impl AsRef<[u8]>) -> Self
87    where
88        Self: Sized,
89    {
90        self.update(data.as_ref());
91        self
92    }
93}
94
95/// Trait for hash functions with fixed-size output.
96pub trait FixedOutput: Update + OutputSizeUser + Sized {
97    /// Consume value and write result into provided array.
98    fn finalize_into(self, out: &mut Output<Self>);
99
100    /// Retrieve result and consume the hasher instance.
101    #[inline]
102    fn finalize_fixed(self) -> Output<Self> {
103        let mut out = Default::default();
104        self.finalize_into(&mut out);
105        out
106    }
107}
108
109/// Trait for hash functions with fixed-size output able to reset themselves.
110pub trait FixedOutputReset: FixedOutput + Reset {
111    /// Write result into provided array and reset the hasher state.
112    fn finalize_into_reset(&mut self, out: &mut Output<Self>);
113
114    /// Retrieve result and reset the hasher state.
115    #[inline]
116    fn finalize_fixed_reset(&mut self) -> Output<Self> {
117        let mut out = Default::default();
118        self.finalize_into_reset(&mut out);
119        out
120    }
121}
122
123/// Trait for reader types which are used to extract extendable output
124/// from a XOF (extendable-output function) result.
125pub trait XofReader {
126    /// Read output into the `buffer`. Can be called an unlimited number of times.
127    fn read(&mut self, buffer: &mut [u8]);
128
129    /// Read output into a boxed slice of the specified size.
130    ///
131    /// Can be called an unlimited number of times in combination with `read`.
132    ///
133    /// `Box<[u8]>` is used instead of `Vec<u8>` to save stack space, since
134    /// they have size of 2 and 3 words respectively.
135    #[cfg(feature = "alloc")]
136    fn read_boxed(&mut self, n: usize) -> Box<[u8]> {
137        let mut buf = vec![0u8; n].into_boxed_slice();
138        self.read(&mut buf);
139        buf
140    }
141}
142
143/// Trait for hash functions with extendable-output (XOF).
144pub trait ExtendableOutput: Sized + Update {
145    /// Reader
146    type Reader: XofReader;
147
148    /// Retrieve XOF reader and consume hasher instance.
149    fn finalize_xof(self) -> Self::Reader;
150
151    /// Finalize XOF and write result into `out`.
152    fn finalize_xof_into(self, out: &mut [u8]) {
153        self.finalize_xof().read(out);
154    }
155
156    /// Compute hash of `data` and write it into `output`.
157    fn digest_xof(input: impl AsRef<[u8]>, output: &mut [u8])
158    where
159        Self: Default,
160    {
161        let mut hasher = Self::default();
162        hasher.update(input.as_ref());
163        hasher.finalize_xof().read(output);
164    }
165
166    /// Retrieve result into a boxed slice of the specified size and consume
167    /// the hasher.
168    ///
169    /// `Box<[u8]>` is used instead of `Vec<u8>` to save stack space, since
170    /// they have size of 2 and 3 words respectively.
171    #[cfg(feature = "alloc")]
172    fn finalize_boxed(self, output_size: usize) -> Box<[u8]> {
173        let mut buf = vec![0u8; output_size].into_boxed_slice();
174        self.finalize_xof().read(&mut buf);
175        buf
176    }
177}
178
179/// Trait for hash functions with extendable-output (XOF) able to reset themselves.
180pub trait ExtendableOutputReset: ExtendableOutput + Reset {
181    /// Retrieve XOF reader and reset hasher instance state.
182    fn finalize_xof_reset(&mut self) -> Self::Reader;
183
184    /// Finalize XOF, write result into `out`, and reset the hasher state.
185    fn finalize_xof_reset_into(&mut self, out: &mut [u8]) {
186        self.finalize_xof_reset().read(out);
187    }
188
189    /// Retrieve result into a boxed slice of the specified size and reset
190    /// the hasher state.
191    ///
192    /// `Box<[u8]>` is used instead of `Vec<u8>` to save stack space, since
193    /// they have size of 2 and 3 words respectively.
194    #[cfg(feature = "alloc")]
195    fn finalize_boxed_reset(&mut self, output_size: usize) -> Box<[u8]> {
196        let mut buf = vec![0u8; output_size].into_boxed_slice();
197        self.finalize_xof_reset().read(&mut buf);
198        buf
199    }
200}
201
202/// Trait for hash functions with customization string for domain separation.
203pub trait CustomizedInit: Sized {
204    /// Create new hasher instance with the given customization string.
205    fn new_customized(customization: &[u8]) -> Self;
206}
207
208/// Types with a certain collision resistance.
209pub trait CollisionResistance {
210    /// Collision resistance in bytes.
211    ///
212    /// This applies to an output size of at least `2 * CollisionResistance` bytes.
213    /// For a smaller output size collision resistance can be usually calculated as
214    /// `min(CollisionResistance, OutputSize / 2)`.
215    type CollisionResistance: Unsigned;
216}
217
218/// The error type used in variable hash traits.
219#[derive(Clone, Copy, Debug, Default)]
220pub struct InvalidOutputSize;
221
222impl fmt::Display for InvalidOutputSize {
223    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
224        f.write_str("invalid output size")
225    }
226}
227
228impl core::error::Error for InvalidOutputSize {}
229
230/// Buffer length is not equal to hash output size.
231#[derive(Default, Debug, Copy, Clone, Eq, PartialEq)]
232pub struct InvalidBufferSize;
233
234impl fmt::Display for InvalidBufferSize {
235    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
236        f.write_str("invalid buffer length")
237    }
238}
239
240impl core::error::Error for InvalidBufferSize {}