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 crypto_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;
62#[cfg(feature = "oid")]
63pub use const_oid;
64pub use crypto_common;
65
66#[cfg(feature = "const-oid")]
67pub use crate::digest::DynDigestWithOid;
68pub use crate::digest::{Digest, DynDigest, HashMarker};
69#[cfg(feature = "mac")]
70pub use crypto_common::{InnerInit, InvalidLength, Key, KeyInit};
71pub use crypto_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
76#[cfg(feature = "block-api")]
77#[deprecated(
78    since = "0.11.0",
79    note = "`digest::core_api` has been replaced by `digest::block_api`"
80)]
81pub use block_api as core_api;
82
83use core::fmt;
84use crypto_common::typenum::Unsigned;
85
86/// Types which consume data with byte granularity.
87pub trait Update {
88    /// Update state using the provided data.
89    fn update(&mut self, data: &[u8]);
90
91    /// Digest input data in a chained manner.
92    #[must_use]
93    fn chain(mut self, data: impl AsRef<[u8]>) -> Self
94    where
95        Self: Sized,
96    {
97        self.update(data.as_ref());
98        self
99    }
100}
101
102/// Trait for hash functions with fixed-size output.
103pub trait FixedOutput: Update + OutputSizeUser + Sized {
104    /// Consume value and write result into provided array.
105    fn finalize_into(self, out: &mut Output<Self>);
106
107    /// Retrieve result and consume the hasher instance.
108    #[inline]
109    fn finalize_fixed(self) -> Output<Self> {
110        let mut out = Default::default();
111        self.finalize_into(&mut out);
112        out
113    }
114}
115
116/// Trait for hash functions with fixed-size output able to reset themselves.
117pub trait FixedOutputReset: FixedOutput + Reset {
118    /// Write result into provided array and reset the hasher state.
119    fn finalize_into_reset(&mut self, out: &mut Output<Self>);
120
121    /// Retrieve result and reset the hasher state.
122    #[inline]
123    fn finalize_fixed_reset(&mut self) -> Output<Self> {
124        let mut out = Default::default();
125        self.finalize_into_reset(&mut out);
126        out
127    }
128}
129
130/// Trait for reader types which are used to extract extendable output
131/// from a XOF (extendable-output function) result.
132pub trait XofReader {
133    /// Read output into the `buffer`. Can be called an unlimited number of times.
134    fn read(&mut self, buffer: &mut [u8]);
135
136    /// Read output into a boxed slice of the specified size.
137    ///
138    /// Can be called an unlimited number of times in combination with `read`.
139    ///
140    /// `Box<[u8]>` is used instead of `Vec<u8>` to save stack space, since
141    /// they have size of 2 and 3 words respectively.
142    #[cfg(feature = "alloc")]
143    fn read_boxed(&mut self, n: usize) -> Box<[u8]> {
144        let mut buf = vec![0u8; n].into_boxed_slice();
145        self.read(&mut buf);
146        buf
147    }
148}
149
150/// Trait for hash functions with extendable-output (XOF).
151pub trait ExtendableOutput: Sized + Update {
152    /// Reader
153    type Reader: XofReader;
154
155    /// Retrieve XOF reader and consume hasher instance.
156    fn finalize_xof(self) -> Self::Reader;
157
158    /// Finalize XOF and write result into `out`.
159    fn finalize_xof_into(self, out: &mut [u8]) {
160        self.finalize_xof().read(out);
161    }
162
163    /// Compute hash of `data` and write it into `output`.
164    fn digest_xof(input: impl AsRef<[u8]>, output: &mut [u8])
165    where
166        Self: Default,
167    {
168        let mut hasher = Self::default();
169        hasher.update(input.as_ref());
170        hasher.finalize_xof().read(output);
171    }
172
173    /// Retrieve result into a boxed slice of the specified size and consume
174    /// the hasher.
175    ///
176    /// `Box<[u8]>` is used instead of `Vec<u8>` to save stack space, since
177    /// they have size of 2 and 3 words respectively.
178    #[cfg(feature = "alloc")]
179    fn finalize_boxed(self, output_size: usize) -> Box<[u8]> {
180        let mut buf = vec![0u8; output_size].into_boxed_slice();
181        self.finalize_xof().read(&mut buf);
182        buf
183    }
184}
185
186/// Trait for hash functions with extendable-output (XOF) able to reset themselves.
187pub trait ExtendableOutputReset: ExtendableOutput + Reset {
188    /// Retrieve XOF reader and reset hasher instance state.
189    fn finalize_xof_reset(&mut self) -> Self::Reader;
190
191    /// Finalize XOF, write result into `out`, and reset the hasher state.
192    fn finalize_xof_reset_into(&mut self, out: &mut [u8]) {
193        self.finalize_xof_reset().read(out);
194    }
195
196    /// Retrieve result into a boxed slice of the specified size and reset
197    /// the hasher state.
198    ///
199    /// `Box<[u8]>` is used instead of `Vec<u8>` to save stack space, since
200    /// they have size of 2 and 3 words respectively.
201    #[cfg(feature = "alloc")]
202    fn finalize_boxed_reset(&mut self, output_size: usize) -> Box<[u8]> {
203        let mut buf = vec![0u8; output_size].into_boxed_slice();
204        self.finalize_xof_reset().read(&mut buf);
205        buf
206    }
207}
208
209/// Trait for hash functions with customization string for domain separation.
210pub trait CustomizedInit: Sized {
211    /// Create new hasher instance with the given customization string.
212    fn new_customized(customization: &[u8]) -> Self;
213}
214
215/// Types with a certain collision resistance.
216pub trait CollisionResistance {
217    /// Collision resistance in bytes.
218    ///
219    /// This applies to an output size of at least `2 * CollisionResistance` bytes.
220    /// For a smaller output size collision resistance can be usually calculated as
221    /// `min(CollisionResistance, OutputSize / 2)`.
222    type CollisionResistance: Unsigned;
223}
224
225/// The error type used in variable hash traits.
226#[derive(Clone, Copy, Debug, Default)]
227pub struct InvalidOutputSize;
228
229impl fmt::Display for InvalidOutputSize {
230    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
231        f.write_str("invalid output size")
232    }
233}
234
235impl core::error::Error for InvalidOutputSize {}
236
237/// Buffer length is not equal to hash output size.
238#[derive(Default, Debug, Copy, Clone, Eq, PartialEq)]
239pub struct InvalidBufferSize;
240
241impl fmt::Display for InvalidBufferSize {
242    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
243        f.write_str("invalid buffer length")
244    }
245}
246
247impl core::error::Error for InvalidBufferSize {}