crypto_common/
lib.rs

1//! Common cryptographic traits.
2
3#![no_std]
4#![cfg_attr(docsrs, feature(doc_cfg))]
5#![doc(
6    html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg",
7    html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg"
8)]
9#![forbid(unsafe_code)]
10#![warn(missing_docs, rust_2018_idioms, missing_debug_implementations)]
11
12/// Hazardous materials.
13pub mod hazmat;
14
15/// Secure random generation.
16#[cfg(feature = "rand_core")]
17mod generate;
18
19pub use hybrid_array as array;
20pub use hybrid_array::typenum;
21
22#[cfg(feature = "getrandom")]
23pub use getrandom;
24#[cfg(feature = "rand_core")]
25pub use {generate::Generate, rand_core};
26
27use core::fmt;
28use hybrid_array::{
29    Array, ArraySize,
30    typenum::{Diff, Sum, Unsigned},
31};
32
33#[cfg(feature = "rand_core")]
34use rand_core::CryptoRng;
35
36/// Block on which [`BlockSizeUser`] implementors operate.
37pub type Block<B> = Array<u8, <B as BlockSizeUser>::BlockSize>;
38
39/// Parallel blocks on which [`ParBlocksSizeUser`] implementors operate.
40pub type ParBlocks<T> = Array<Block<T>, <T as ParBlocksSizeUser>::ParBlocksSize>;
41
42/// Output array of [`OutputSizeUser`] implementors.
43pub type Output<T> = Array<u8, OutputSize<T>>;
44
45/// Alias for the output size of [`OutputSizeUser`] implementors.
46pub type OutputSize<T> = <T as OutputSizeUser>::OutputSize;
47
48/// Key used by [`KeySizeUser`] implementors.
49pub type Key<B> = Array<u8, <B as KeySizeUser>::KeySize>;
50
51/// Initialization vector (nonce) used by [`IvSizeUser`] implementors.
52pub type Iv<B> = Array<u8, <B as IvSizeUser>::IvSize>;
53
54/// Alias for `AddBlockSize<A, B> = Sum<T, B::BlockSize>`
55pub type AddBlockSize<T, B> = Sum<T, <B as BlockSizeUser>::BlockSize>;
56
57/// Alias for `SubBlockSize<A, B> = Diff<T, B::BlockSize>`
58pub type SubBlockSize<T, B> = Diff<T, <B as BlockSizeUser>::BlockSize>;
59
60/// Types which process data in blocks.
61pub trait BlockSizeUser {
62    /// Size of the block in bytes.
63    type BlockSize: BlockSizes;
64
65    /// Return block size in bytes.
66    #[inline(always)]
67    fn block_size() -> usize {
68        Self::BlockSize::USIZE
69    }
70}
71
72impl<T: BlockSizeUser> BlockSizeUser for &T {
73    type BlockSize = T::BlockSize;
74}
75
76impl<T: BlockSizeUser> BlockSizeUser for &mut T {
77    type BlockSize = T::BlockSize;
78}
79
80/// Trait implemented for supported block sizes, i.e. for types from `U1` to `U255`.
81pub trait BlockSizes: ArraySize + sealed::BlockSizes {}
82
83impl<T: ArraySize + sealed::BlockSizes> BlockSizes for T {}
84
85mod sealed {
86    use crate::typenum::{IsLess, NonZero, True, U256, Unsigned};
87
88    pub trait BlockSizes {}
89
90    impl<T: Unsigned> BlockSizes for T where Self: IsLess<U256, Output = True> + NonZero {}
91}
92
93/// Types which can process blocks in parallel.
94pub trait ParBlocksSizeUser: BlockSizeUser {
95    /// Number of blocks which can be processed in parallel.
96    type ParBlocksSize: ArraySize;
97}
98
99/// Types which return data with the given size.
100pub trait OutputSizeUser {
101    /// Size of the output in bytes.
102    type OutputSize: ArraySize;
103
104    /// Return output size in bytes.
105    #[inline(always)]
106    fn output_size() -> usize {
107        Self::OutputSize::USIZE
108    }
109}
110
111/// Types which use key for initialization.
112///
113/// Generally it's used indirectly via [`KeyInit`] or [`KeyIvInit`].
114pub trait KeySizeUser {
115    /// Key size in bytes.
116    type KeySize: ArraySize;
117
118    /// Return key size in bytes.
119    #[inline(always)]
120    fn key_size() -> usize {
121        Self::KeySize::USIZE
122    }
123}
124
125/// Types which use initialization vector (nonce) for initialization.
126///
127/// Generally it's used indirectly via [`KeyIvInit`] or [`InnerIvInit`].
128pub trait IvSizeUser {
129    /// Initialization vector size in bytes.
130    type IvSize: ArraySize;
131
132    /// Return IV size in bytes.
133    #[inline(always)]
134    fn iv_size() -> usize {
135        Self::IvSize::USIZE
136    }
137}
138
139/// Types which use another type for initialization.
140///
141/// Generally it's used indirectly via [`InnerInit`] or [`InnerIvInit`].
142pub trait InnerUser {
143    /// Inner type.
144    type Inner;
145}
146
147/// Resettable types.
148pub trait Reset {
149    /// Reset state to its initial value.
150    fn reset(&mut self);
151}
152
153/// Trait which stores algorithm name constant, used in `Debug` implementations.
154pub trait AlgorithmName {
155    /// Write algorithm name into `f`.
156    fn write_alg_name(f: &mut fmt::Formatter<'_>) -> fmt::Result;
157}
158
159/// Types which can be initialized from a key.
160pub trait KeyInit: KeySizeUser + Sized {
161    /// Create new value from fixed size key.
162    fn new(key: &Key<Self>) -> Self;
163
164    /// Check if the key might be considered weak.
165    #[inline]
166    fn weak_key_test(_key: &Key<Self>) -> Result<(), WeakKeyError> {
167        Ok(())
168    }
169
170    /// Create new value from fixed size key after checking it for weakness.
171    #[inline]
172    fn new_checked(key: &Key<Self>) -> Result<Self, WeakKeyError> {
173        Self::weak_key_test(key)?;
174        Ok(Self::new(key))
175    }
176
177    /// Create new value from variable size key.
178    #[inline]
179    fn new_from_slice(key: &[u8]) -> Result<Self, InvalidLength> {
180        <&Key<Self>>::try_from(key)
181            .map(Self::new)
182            .map_err(|_| InvalidLength)
183    }
184
185    /// DEPRECATED: generate random key using the provided [`CryptoRng`].
186    ///
187    /// Instead, you can now use the [`Generate`] trait directly with the [`Key`] type:
188    ///
189    /// ```ignore
190    /// let key = Key::generate_from_rng(rng);
191    /// ```
192    #[deprecated(
193        since = "0.2.0",
194        note = "use the `Generate` trait impl on `Key` instead"
195    )]
196    #[cfg(feature = "rand_core")]
197    fn generate_key<R: CryptoRng>(rng: &mut R) -> Key<Self> {
198        Key::<Self>::generate_from_rng(rng)
199    }
200}
201
202/// Types which can be initialized from a key and initialization vector (nonce).
203pub trait KeyIvInit: KeySizeUser + IvSizeUser + Sized {
204    /// Create new value from fixed length key and nonce.
205    fn new(key: &Key<Self>, iv: &Iv<Self>) -> Self;
206
207    /// Check if the key might be considered weak.
208    #[inline]
209    fn weak_key_test(_key: &Key<Self>) -> Result<(), WeakKeyError> {
210        Ok(())
211    }
212
213    /// Create new value from fixed length key and nonce after checking the key for weakness.
214    #[inline]
215    fn new_checked(key: &Key<Self>, iv: &Iv<Self>) -> Result<Self, WeakKeyError> {
216        Self::weak_key_test(key)?;
217        Ok(Self::new(key, iv))
218    }
219
220    /// Create new value from variable length key and nonce.
221    #[inline]
222    fn new_from_slices(key: &[u8], iv: &[u8]) -> Result<Self, InvalidLength> {
223        let key = <&Key<Self>>::try_from(key).map_err(|_| InvalidLength)?;
224        let iv = <&Iv<Self>>::try_from(iv).map_err(|_| InvalidLength)?;
225        Ok(Self::new(key, iv))
226    }
227
228    /// DEPRECATED: generate random key using the provided [`CryptoRng`].
229    ///
230    /// Instead, you can now use the [`Generate`] trait directly with the [`Key`] type:
231    ///
232    /// ```ignore
233    /// let key = Key::generate_from_rng(rng);
234    /// ```
235    #[deprecated(
236        since = "0.2.0",
237        note = "use the `Generate` trait impl on `Key` instead"
238    )]
239    #[cfg(feature = "rand_core")]
240    fn generate_key<R: CryptoRng>(rng: &mut R) -> Key<Self> {
241        Key::<Self>::generate_from_rng(rng)
242    }
243
244    /// DEPRECATED: generate random IV using the provided [`CryptoRng`].
245    ///
246    /// Instead, you can now use the [`Generate`] trait directly with the [`Iv`] type:
247    ///
248    /// ```ignore
249    /// let iv = Iv::generate_from_rng(rng);
250    /// ```
251    #[deprecated(
252        since = "0.2.0",
253        note = "use the `Generate` trait impl on `Iv` instead"
254    )]
255    #[cfg(feature = "rand_core")]
256    fn generate_iv<R: CryptoRng>(rng: &mut R) -> Iv<Self> {
257        Iv::<Self>::generate_from_rng(rng)
258    }
259
260    /// DEPRECATED: generate random key and IV using the provided [`CryptoRng`].
261    ///
262    /// Instead, you can now use the [`Generate`] trait directly with the [`Key`] and [`Iv`] types:
263    ///
264    /// ```ignore
265    /// let key = Key::generate_from_rng(rng);
266    /// let iv = Iv::generate_from_rng(rng);
267    /// ```
268    #[deprecated(
269        since = "0.2.0",
270        note = "use the `Generate` trait impls on `Key` and `Iv` instead"
271    )]
272    #[cfg(feature = "rand_core")]
273    fn generate_key_iv<R: CryptoRng>(rng: &mut R) -> (Key<Self>, Iv<Self>) {
274        let key = Key::<Self>::generate_from_rng(rng);
275        let iv = Iv::<Self>::generate_from_rng(rng);
276        (key, iv)
277    }
278}
279
280/// Types which can be fallibly initialized from a key.
281pub trait TryKeyInit: KeySizeUser + Sized {
282    /// Create new value from a fixed-size key.
283    ///
284    /// # Errors
285    /// - if the key is considered invalid according to rules specific to the implementing type
286    fn new(key: &Key<Self>) -> Result<Self, InvalidKey>;
287
288    /// Create new value from a variable size key.
289    ///
290    /// # Errors
291    /// - if the provided slice is the wrong length
292    /// - if the key is considered invalid by [`TryKeyInit::new`]
293    #[inline]
294    fn new_from_slice(key: &[u8]) -> Result<Self, InvalidKey> {
295        <&Key<Self>>::try_from(key)
296            .map_err(|_| InvalidKey)
297            .and_then(Self::new)
298    }
299}
300
301/// Types which can be initialized from another type (usually block ciphers).
302///
303/// Usually used for initializing types from block ciphers.
304pub trait InnerInit: InnerUser + Sized {
305    /// Initialize value from the `inner`.
306    fn inner_init(inner: Self::Inner) -> Self;
307}
308
309/// Types which can be initialized from another type and additional initialization
310/// vector/nonce.
311///
312/// Usually used for initializing types from block ciphers.
313pub trait InnerIvInit: InnerUser + IvSizeUser + Sized {
314    /// Initialize value using `inner` and `iv` array.
315    fn inner_iv_init(inner: Self::Inner, iv: &Iv<Self>) -> Self;
316
317    /// Initialize value using `inner` and `iv` slice.
318    #[inline]
319    fn inner_iv_slice_init(inner: Self::Inner, iv: &[u8]) -> Result<Self, InvalidLength> {
320        let iv = <&Iv<Self>>::try_from(iv).map_err(|_| InvalidLength)?;
321        Ok(Self::inner_iv_init(inner, iv))
322    }
323}
324
325/// Trait for loading current IV state.
326pub trait IvState: IvSizeUser {
327    /// Returns current IV state.
328    fn iv_state(&self) -> Iv<Self>;
329}
330
331impl<T> KeySizeUser for T
332where
333    T: InnerUser,
334    T::Inner: KeySizeUser,
335{
336    type KeySize = <T::Inner as KeySizeUser>::KeySize;
337}
338
339impl<T> KeyIvInit for T
340where
341    T: InnerIvInit,
342    T::Inner: KeyInit,
343{
344    #[inline]
345    fn new(key: &Key<Self>, iv: &Iv<Self>) -> Self {
346        Self::inner_iv_init(T::Inner::new(key), iv)
347    }
348
349    #[inline]
350    fn new_from_slices(key: &[u8], iv: &[u8]) -> Result<Self, InvalidLength> {
351        T::Inner::new_from_slice(key).and_then(|i| T::inner_iv_slice_init(i, iv))
352    }
353
354    #[inline]
355    fn weak_key_test(key: &Key<Self>) -> Result<(), WeakKeyError> {
356        T::Inner::weak_key_test(key)
357    }
358}
359
360impl<T> KeyInit for T
361where
362    T: InnerInit,
363    T::Inner: KeyInit,
364{
365    #[inline]
366    fn new(key: &Key<Self>) -> Self {
367        Self::inner_init(T::Inner::new(key))
368    }
369
370    #[inline]
371    fn new_from_slice(key: &[u8]) -> Result<Self, InvalidLength> {
372        T::Inner::new_from_slice(key)
373            .map_err(|_| InvalidLength)
374            .map(Self::inner_init)
375    }
376
377    #[inline]
378    fn weak_key_test(key: &Key<Self>) -> Result<(), WeakKeyError> {
379        T::Inner::weak_key_test(key)
380    }
381}
382
383// Unfortunately this blanket impl is impossible without mutually
384// exclusive traits, see: https://github.com/rust-lang/rfcs/issues/1053
385// or at the very least without: https://github.com/rust-lang/rust/issues/20400
386/*
387impl<T> KeyIvInit for T
388where
389    T: InnerInit,
390    T::Inner: KeyIvInit,
391{
392    #[inline]
393    fn new(key: &Key<Self>, iv: &Iv<Self>) -> Self {
394        Self::inner_init(T::Inner::new(key, iv))
395    }
396
397    #[inline]
398    fn new_from_slices(key: &[u8], iv: &[u8]) -> Result<Self, InvalidLength> {
399        T::Inner::new_from_slice(key)
400            .map_err(|_| InvalidLength)
401            .map(Self::inner_init)
402    }
403
404    #[inline]
405    fn weak_key_test(key: &Key<Self>) -> Result<(), WeakKeyError> {
406        T::Inner::weak_key_test(key)
407    }
408}
409*/
410
411/// Error type for [`TryKeyInit`] for cases where the provided bytes do not correspond to a
412/// valid key.
413#[derive(Copy, Clone, Eq, PartialEq, Debug)]
414pub struct InvalidKey;
415
416impl fmt::Display for InvalidKey {
417    #[inline]
418    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
419        f.write_str("WeakKey")
420    }
421}
422
423impl core::error::Error for InvalidKey {}
424
425/// The error type returned when key and/or IV used in the [`KeyInit`],
426/// [`KeyIvInit`], and [`InnerIvInit`] slice-based methods had
427/// an invalid length.
428#[derive(Copy, Clone, Eq, PartialEq, Debug)]
429pub struct InvalidLength;
430
431impl fmt::Display for InvalidLength {
432    #[inline]
433    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
434        f.write_str("Invalid Length")
435    }
436}
437
438impl core::error::Error for InvalidLength {}
439
440/// The error type returned when a key is found to be weak.
441#[derive(Copy, Clone, Eq, PartialEq, Debug)]
442pub struct WeakKeyError;
443
444impl fmt::Display for WeakKeyError {
445    #[inline]
446    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
447        f.write_str("WeakKey")
448    }
449}
450
451impl core::error::Error for WeakKeyError {}