Skip to main content

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/// Serialize a key to a byte array.
160pub trait KeyExport: KeySizeUser {
161    /// Serialize this key as a byte array.
162    fn to_bytes(&self) -> Key<Self>;
163}
164
165/// Types which can be initialized from a key.
166pub trait KeyInit: KeySizeUser + Sized {
167    /// Create new value from fixed size key.
168    fn new(key: &Key<Self>) -> Self;
169
170    /// Create new value from variable size key.
171    #[inline]
172    fn new_from_slice(key: &[u8]) -> Result<Self, InvalidLength> {
173        <&Key<Self>>::try_from(key)
174            .map(Self::new)
175            .map_err(|_| InvalidLength)
176    }
177
178    /// DEPRECATED: generate random key using the provided [`CryptoRng`].
179    ///
180    /// Instead, you can now use the [`Generate`] trait directly with the [`Key`] type:
181    ///
182    /// ```ignore
183    /// let key = Key::generate_from_rng(rng);
184    /// ```
185    #[deprecated(
186        since = "0.2.0",
187        note = "use the `Generate` trait impl on `Key` instead"
188    )]
189    #[cfg(feature = "rand_core")]
190    fn generate_key<R: CryptoRng>(rng: &mut R) -> Key<Self> {
191        Key::<Self>::generate_from_rng(rng)
192    }
193}
194
195/// Types which can be initialized from a key and initialization vector (nonce).
196pub trait KeyIvInit: KeySizeUser + IvSizeUser + Sized {
197    /// Create new value from fixed length key and nonce.
198    fn new(key: &Key<Self>, iv: &Iv<Self>) -> Self;
199
200    /// Create new value from variable length key and nonce.
201    #[inline]
202    fn new_from_slices(key: &[u8], iv: &[u8]) -> Result<Self, InvalidLength> {
203        let key = <&Key<Self>>::try_from(key).map_err(|_| InvalidLength)?;
204        let iv = <&Iv<Self>>::try_from(iv).map_err(|_| InvalidLength)?;
205        Ok(Self::new(key, iv))
206    }
207
208    /// DEPRECATED: generate random key using the provided [`CryptoRng`].
209    ///
210    /// Instead, you can now use the [`Generate`] trait directly with the [`Key`] type:
211    ///
212    /// ```ignore
213    /// let key = Key::generate_from_rng(rng);
214    /// ```
215    #[deprecated(
216        since = "0.2.0",
217        note = "use the `Generate` trait impl on `Key` instead"
218    )]
219    #[cfg(feature = "rand_core")]
220    fn generate_key<R: CryptoRng>(rng: &mut R) -> Key<Self> {
221        Key::<Self>::generate_from_rng(rng)
222    }
223
224    /// DEPRECATED: generate random IV using the provided [`CryptoRng`].
225    ///
226    /// Instead, you can now use the [`Generate`] trait directly with the [`Iv`] type:
227    ///
228    /// ```ignore
229    /// let iv = Iv::generate_from_rng(rng);
230    /// ```
231    #[deprecated(
232        since = "0.2.0",
233        note = "use the `Generate` trait impl on `Iv` instead"
234    )]
235    #[cfg(feature = "rand_core")]
236    fn generate_iv<R: CryptoRng>(rng: &mut R) -> Iv<Self> {
237        Iv::<Self>::generate_from_rng(rng)
238    }
239
240    /// DEPRECATED: generate random key and IV using the provided [`CryptoRng`].
241    ///
242    /// Instead, you can now use the [`Generate`] trait directly with the [`Key`] and [`Iv`] types:
243    ///
244    /// ```ignore
245    /// let key = Key::generate_from_rng(rng);
246    /// let iv = Iv::generate_from_rng(rng);
247    /// ```
248    #[deprecated(
249        since = "0.2.0",
250        note = "use the `Generate` trait impls on `Key` and `Iv` instead"
251    )]
252    #[cfg(feature = "rand_core")]
253    fn generate_key_iv<R: CryptoRng>(rng: &mut R) -> (Key<Self>, Iv<Self>) {
254        let key = Key::<Self>::generate_from_rng(rng);
255        let iv = Iv::<Self>::generate_from_rng(rng);
256        (key, iv)
257    }
258}
259
260/// Types which can be fallibly initialized from a key.
261pub trait TryKeyInit: KeySizeUser + Sized {
262    /// Create new value from a fixed-size key.
263    ///
264    /// # Errors
265    /// - if the key is considered invalid according to rules specific to the implementing type
266    fn new(key: &Key<Self>) -> Result<Self, InvalidKey>;
267
268    /// Create new value from a variable size key.
269    ///
270    /// # Errors
271    /// - if the provided slice is the wrong length
272    /// - if the key is considered invalid by [`TryKeyInit::new`]
273    #[inline]
274    fn new_from_slice(key: &[u8]) -> Result<Self, InvalidKey> {
275        <&Key<Self>>::try_from(key)
276            .map_err(|_| InvalidKey)
277            .and_then(Self::new)
278    }
279}
280
281/// Types which can be initialized from another type (usually block ciphers).
282///
283/// Usually used for initializing types from block ciphers.
284pub trait InnerInit: InnerUser + Sized {
285    /// Initialize value from the `inner`.
286    fn inner_init(inner: Self::Inner) -> Self;
287}
288
289/// Types which can be initialized from another type and additional initialization
290/// vector/nonce.
291///
292/// Usually used for initializing types from block ciphers.
293pub trait InnerIvInit: InnerUser + IvSizeUser + Sized {
294    /// Initialize value using `inner` and `iv` array.
295    fn inner_iv_init(inner: Self::Inner, iv: &Iv<Self>) -> Self;
296
297    /// Initialize value using `inner` and `iv` slice.
298    #[inline]
299    fn inner_iv_slice_init(inner: Self::Inner, iv: &[u8]) -> Result<Self, InvalidLength> {
300        let iv = <&Iv<Self>>::try_from(iv).map_err(|_| InvalidLength)?;
301        Ok(Self::inner_iv_init(inner, iv))
302    }
303}
304
305/// Trait for loading current IV state.
306pub trait IvState: IvSizeUser {
307    /// Returns current IV state.
308    fn iv_state(&self) -> Iv<Self>;
309}
310
311impl<T> KeySizeUser for T
312where
313    T: InnerUser,
314    T::Inner: KeySizeUser,
315{
316    type KeySize = <T::Inner as KeySizeUser>::KeySize;
317}
318
319impl<T> KeyIvInit for T
320where
321    T: InnerIvInit,
322    T::Inner: KeyInit,
323{
324    #[inline]
325    fn new(key: &Key<Self>, iv: &Iv<Self>) -> Self {
326        Self::inner_iv_init(T::Inner::new(key), iv)
327    }
328
329    #[inline]
330    fn new_from_slices(key: &[u8], iv: &[u8]) -> Result<Self, InvalidLength> {
331        T::Inner::new_from_slice(key).and_then(|i| T::inner_iv_slice_init(i, iv))
332    }
333}
334
335impl<T> KeyInit for T
336where
337    T: InnerInit,
338    T::Inner: KeyInit,
339{
340    #[inline]
341    fn new(key: &Key<Self>) -> Self {
342        Self::inner_init(T::Inner::new(key))
343    }
344
345    #[inline]
346    fn new_from_slice(key: &[u8]) -> Result<Self, InvalidLength> {
347        T::Inner::new_from_slice(key)
348            .map_err(|_| InvalidLength)
349            .map(Self::inner_init)
350    }
351}
352
353// Unfortunately this blanket impl is impossible without mutually
354// exclusive traits, see: https://github.com/rust-lang/rfcs/issues/1053
355// or at the very least without: https://github.com/rust-lang/rust/issues/20400
356/*
357impl<T> KeyIvInit for T
358where
359    T: InnerInit,
360    T::Inner: KeyIvInit,
361{
362    #[inline]
363    fn new(key: &Key<Self>, iv: &Iv<Self>) -> Self {
364        Self::inner_init(T::Inner::new(key, iv))
365    }
366
367    #[inline]
368    fn new_from_slices(key: &[u8], iv: &[u8]) -> Result<Self, InvalidLength> {
369        T::Inner::new_from_slice(key)
370            .map_err(|_| InvalidLength)
371            .map(Self::inner_init)
372    }
373}
374*/
375
376/// Error type for [`TryKeyInit`] for cases where the provided bytes do not correspond to a
377/// valid key.
378#[derive(Copy, Clone, Eq, PartialEq, Debug)]
379pub struct InvalidKey;
380
381impl fmt::Display for InvalidKey {
382    #[inline]
383    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
384        f.write_str("InvalidKey")
385    }
386}
387
388impl core::error::Error for InvalidKey {}
389
390/// The error type returned when key and/or IV used in the [`KeyInit`],
391/// [`KeyIvInit`], and [`InnerIvInit`] slice-based methods had
392/// an invalid length.
393#[derive(Copy, Clone, Eq, PartialEq, Debug)]
394pub struct InvalidLength;
395
396impl fmt::Display for InvalidLength {
397    #[inline]
398    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
399        f.write_str("Invalid Length")
400    }
401}
402
403impl core::error::Error for InvalidLength {}