Vendor dependencies

This commit is contained in:
2026-08-01 16:11:49 +03:00
parent 7f139a0241
commit 6b5e7f0f8b
29706 changed files with 9575646 additions and 0 deletions
+92
View File
@@ -0,0 +1,92 @@
use hybrid_array::{Array, ArraySize};
use rand_core::{CryptoRng, TryCryptoRng};
#[cfg(feature = "getrandom")]
use getrandom::{SysRng, rand_core::UnwrapErr};
/// Secure random generation.
pub trait Generate: Sized {
/// Generate random key using the provided [`TryCryptoRng`].
///
/// # Errors
/// Returns `R::Error` in the event the provided RNG `R` experiences an internal failure.
fn try_generate_from_rng<R: TryCryptoRng + ?Sized>(rng: &mut R) -> Result<Self, R::Error>;
/// Generate random key using the provided [`CryptoRng`].
#[must_use]
fn generate_from_rng<R: CryptoRng + ?Sized>(rng: &mut R) -> Self {
let Ok(ret) = Self::try_generate_from_rng(rng);
ret
}
/// Randomly generate a value of this type using the system's ambient cryptographically secure
/// random number generator.
///
/// # Errors
/// Returns [`getrandom::Error`] in the event the system's ambient RNG experiences an internal
/// failure.
#[cfg(feature = "getrandom")]
fn try_generate() -> Result<Self, getrandom::Error> {
Self::try_generate_from_rng(&mut SysRng)
}
/// Randomly generate a value of this type using the system's ambient cryptographically secure
/// random number generator.
///
/// # Panics
/// This method will panic in the event the system's ambient RNG experiences an internal
/// failure.
///
/// This shouldn't happen on most modern operating systems.
#[cfg(feature = "getrandom")]
#[must_use]
fn generate() -> Self {
Self::generate_from_rng(&mut UnwrapErr(SysRng))
}
}
impl Generate for u32 {
#[inline]
fn try_generate_from_rng<R: TryCryptoRng + ?Sized>(rng: &mut R) -> Result<Self, R::Error> {
rng.try_next_u32()
}
}
impl Generate for u64 {
#[inline]
fn try_generate_from_rng<R: TryCryptoRng + ?Sized>(rng: &mut R) -> Result<Self, R::Error> {
rng.try_next_u64()
}
}
impl<const N: usize> Generate for [u8; N] {
#[inline]
fn try_generate_from_rng<R: TryCryptoRng + ?Sized>(rng: &mut R) -> Result<Self, R::Error> {
let mut ret = [0u8; N];
rng.try_fill_bytes(&mut ret)?;
Ok(ret)
}
}
impl<U: ArraySize> Generate for Array<u8, U> {
#[inline]
fn try_generate_from_rng<R: TryCryptoRng + ?Sized>(rng: &mut R) -> Result<Self, R::Error> {
let mut ret = Self::default();
rng.try_fill_bytes(&mut ret)?;
Ok(ret)
}
}
impl<U: ArraySize> Generate for Array<u32, U> {
#[inline]
fn try_generate_from_rng<R: TryCryptoRng + ?Sized>(rng: &mut R) -> Result<Self, R::Error> {
Self::try_from_fn(|_| rng.try_next_u32())
}
}
impl<U: ArraySize> Generate for Array<u64, U> {
#[inline]
fn try_generate_from_rng<R: TryCryptoRng + ?Sized>(rng: &mut R) -> Result<Self, R::Error> {
Self::try_from_fn(|_| rng.try_next_u64())
}
}
+363
View File
@@ -0,0 +1,363 @@
use crate::array::{
Array, ArraySize, sizes,
typenum::{Diff, Prod, Sum, U1, U2, U4, U8, U16, Unsigned},
};
use core::{convert::TryInto, default::Default, fmt};
/// Serialized internal state.
pub type SerializedState<T> = Array<u8, <T as SerializableState>::SerializedStateSize>;
/// Alias for `AddSerializedStateSize<T, S> = Sum<T, S::SerializedStateSize>`
pub type AddSerializedStateSize<T, S> = Sum<T, <S as SerializableState>::SerializedStateSize>;
/// Alias for `SubSerializedStateSize<T, S> = Diff<T, S::SerializedStateSize>`
pub type SubSerializedStateSize<T, S> = Diff<T, <S as SerializableState>::SerializedStateSize>;
/// The error type returned when an object cannot be deserialized from the state.
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub struct DeserializeStateError;
impl fmt::Display for DeserializeStateError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
f.write_str("Deserialization error")
}
}
impl core::error::Error for DeserializeStateError {}
/// Types which can serialize the internal state and be restored from it.
///
/// # Compatibility
///
/// Serialized state can be assumed to be stable across backwards compatible
/// versions of an implementation crate, i.e. any `0.x.y` version of a crate
/// should be able to decode data serialized with any other `0.x.z` version,
/// but it may not be able to correctly decode data serialized with a non-`x`
/// version.
///
/// This guarantee is a subject to issues such as security fixes.
///
/// # SECURITY WARNING
///
/// Serialized state may contain sensitive data.
pub trait SerializableState
where
Self: Sized,
{
/// Size of serialized internal state.
type SerializedStateSize: ArraySize;
/// Serialize and return internal state.
fn serialize(&self) -> SerializedState<Self>;
/// Create an object from serialized internal state.
///
/// # Errors
/// If the serialized state could not be deserialized successfully.
fn deserialize(serialized_state: &SerializedState<Self>)
-> Result<Self, DeserializeStateError>;
}
macro_rules! impl_seializable_state_unsigned {
($type: ty, $type_size: ty) => {
impl SerializableState for $type {
type SerializedStateSize = $type_size;
fn serialize(&self) -> SerializedState<Self> {
self.to_le_bytes().into()
}
fn deserialize(
serialized_state: &SerializedState<Self>,
) -> Result<Self, DeserializeStateError> {
Ok(<$type>::from_le_bytes((*serialized_state).into()))
}
}
};
}
impl_seializable_state_unsigned!(u8, U1);
impl_seializable_state_unsigned!(u16, U2);
impl_seializable_state_unsigned!(u32, U4);
impl_seializable_state_unsigned!(u64, U8);
impl_seializable_state_unsigned!(u128, U16);
macro_rules! impl_serializable_state_u8_array {
($($n: ident),*) => {
$(
impl SerializableState for [u8; sizes::$n::USIZE] {
type SerializedStateSize = sizes::$n;
fn serialize(&self) -> SerializedState<Self> {
(*self).into()
}
fn deserialize(
serialized_state: &SerializedState<Self>,
) -> Result<Self, DeserializeStateError> {
Ok((*serialized_state).into())
}
}
)*
};
}
macro_rules! impl_serializable_state_type_array {
($type: ty, $type_size: ty, $n: ident) => {
impl SerializableState for [$type; sizes::$n::USIZE] {
type SerializedStateSize = Prod<sizes::$n, $type_size>;
fn serialize(&self) -> SerializedState<Self> {
let mut serialized_state = SerializedState::<Self>::default();
for (val, chunk) in self
.iter()
.zip(serialized_state.chunks_exact_mut(<$type_size>::USIZE))
{
chunk.copy_from_slice(&val.to_le_bytes());
}
serialized_state
}
fn deserialize(
serialized_state: &SerializedState<Self>,
) -> Result<Self, DeserializeStateError> {
let mut array = [0; sizes::$n::USIZE];
for (val, chunk) in array
.iter_mut()
.zip(serialized_state.chunks_exact(<$type_size>::USIZE))
{
*val = <$type>::from_le_bytes(chunk.try_into().unwrap());
}
Ok(array)
}
}
};
}
macro_rules! impl_serializable_state_u16_array {
($($n: ident),*) => {
$(
impl_serializable_state_type_array!(u16, U2, $n);
)*
};
}
macro_rules! impl_serializable_state_u32_array {
($($n: ident),*) => {
$(
impl_serializable_state_type_array!(u32, U4, $n);
)*
};
}
macro_rules! impl_serializable_state_u64_array {
($($n: ident),*) => {
$(
impl_serializable_state_type_array!(u64, U8, $n);
)*
};
}
macro_rules! impl_serializable_state_u128_array {
($($n: ident),*) => {
$(
impl_serializable_state_type_array!(u128, U8, $n);
)*
};
}
impl_serializable_state_u8_array! {
U1,
U2,
U3,
U4,
U5,
U6,
U7,
U8,
U9,
U10,
U11,
U12,
U13,
U14,
U15,
U16,
U17,
U18,
U19,
U20,
U21,
U22,
U23,
U24,
U25,
U26,
U27,
U28,
U29,
U30,
U31,
U32,
U33,
U34,
U35,
U36,
U37,
U38,
U39,
U40,
U41,
U42,
U43,
U44,
U45,
U46,
U47,
U48,
U49,
U50,
U51,
U52,
U53,
U54,
U55,
U56,
U57,
U58,
U59,
U60,
U61,
U62,
U63,
U64,
U96,
U128,
U192,
U256,
U384,
U448,
U512,
U768,
U896,
U1024,
U2048,
U4096,
U8192
}
impl_serializable_state_u16_array! {
U1,
U2,
U3,
U4,
U5,
U6,
U7,
U8,
U9,
U10,
U11,
U12,
U13,
U14,
U15,
U16,
U17,
U18,
U19,
U20,
U21,
U22,
U23,
U24,
U25,
U26,
U27,
U28,
U29,
U30,
U31,
U32,
U48,
U96,
U128,
U192,
U256,
U384,
U448,
U512,
U2048,
U4096
}
impl_serializable_state_u32_array! {
U1,
U2,
U3,
U4,
U5,
U6,
U7,
U8,
U9,
U10,
U11,
U12,
U13,
U14,
U15,
U16,
U24,
U32,
U48,
U64,
U96,
U128,
U192,
U256,
U512,
U1024,
U2048
}
impl_serializable_state_u64_array! {
U1,
U2,
U3,
U4,
U5,
U6,
U7,
U8,
U12,
U16,
U24,
U32,
U48,
U64,
U96,
U128,
U256,
U512,
U1024
}
impl_serializable_state_u128_array! {
U1,
U2,
U3,
U4,
U6,
U8,
U12,
U16,
U24,
U32,
U48,
U64,
U128,
U256,
U512
}
+398
View File
@@ -0,0 +1,398 @@
#![no_std]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![doc = include_str!("../README.md")]
#![doc(
html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/8f1a9894/logo.svg",
html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/8f1a9894/logo.svg"
)]
#![forbid(unsafe_code)]
/// Hazardous materials.
pub mod hazmat;
/// Secure random generation.
#[cfg(feature = "rand_core")]
mod generate;
pub use hybrid_array as array;
pub use hybrid_array::typenum;
#[cfg(feature = "getrandom")]
pub use getrandom;
#[cfg(feature = "rand_core")]
pub use {generate::Generate, rand_core};
use core::fmt;
use hybrid_array::{
Array, ArraySize,
typenum::{Diff, Sum, Unsigned},
};
#[cfg(feature = "rand_core")]
use rand_core::CryptoRng;
/// Block on which [`BlockSizeUser`] implementors operate.
pub type Block<B> = Array<u8, <B as BlockSizeUser>::BlockSize>;
/// Parallel blocks on which [`ParBlocksSizeUser`] implementors operate.
pub type ParBlocks<T> = Array<Block<T>, <T as ParBlocksSizeUser>::ParBlocksSize>;
/// Output array of [`OutputSizeUser`] implementors.
pub type Output<T> = Array<u8, OutputSize<T>>;
/// Alias for the output size of [`OutputSizeUser`] implementors.
pub type OutputSize<T> = <T as OutputSizeUser>::OutputSize;
/// Key used by [`KeySizeUser`] implementors.
pub type Key<B> = Array<u8, <B as KeySizeUser>::KeySize>;
/// Initialization vector (nonce) used by [`IvSizeUser`] implementors.
pub type Iv<B> = Array<u8, <B as IvSizeUser>::IvSize>;
/// Alias for `AddBlockSize<A, B> = Sum<T, B::BlockSize>`
pub type AddBlockSize<T, B> = Sum<T, <B as BlockSizeUser>::BlockSize>;
/// Alias for `SubBlockSize<A, B> = Diff<T, B::BlockSize>`
pub type SubBlockSize<T, B> = Diff<T, <B as BlockSizeUser>::BlockSize>;
/// Types which process data in blocks.
pub trait BlockSizeUser {
/// Size of the block in bytes.
type BlockSize: ArraySize;
/// Return block size in bytes.
#[inline(always)]
#[must_use]
fn block_size() -> usize {
Self::BlockSize::USIZE
}
}
impl<T: BlockSizeUser> BlockSizeUser for &T {
type BlockSize = T::BlockSize;
}
impl<T: BlockSizeUser> BlockSizeUser for &mut T {
type BlockSize = T::BlockSize;
}
/// Types which can process blocks in parallel.
pub trait ParBlocksSizeUser: BlockSizeUser {
/// Number of blocks which can be processed in parallel.
type ParBlocksSize: ArraySize;
}
/// Types which return data with the given size.
pub trait OutputSizeUser {
/// Size of the output in bytes.
type OutputSize: ArraySize;
/// Return output size in bytes.
#[inline(always)]
#[must_use]
fn output_size() -> usize {
Self::OutputSize::USIZE
}
}
/// Types which use key for initialization.
///
/// Generally it's used indirectly via [`KeyInit`] or [`KeyIvInit`].
pub trait KeySizeUser {
/// Key size in bytes.
type KeySize: ArraySize;
/// Return key size in bytes.
#[inline(always)]
#[must_use]
fn key_size() -> usize {
Self::KeySize::USIZE
}
}
/// Types which use initialization vector (nonce) for initialization.
///
/// Generally it's used indirectly via [`KeyIvInit`] or [`InnerIvInit`].
pub trait IvSizeUser {
/// Initialization vector size in bytes.
type IvSize: ArraySize;
/// Return IV size in bytes.
#[inline(always)]
#[must_use]
fn iv_size() -> usize {
Self::IvSize::USIZE
}
}
/// Types which use another type for initialization.
///
/// Generally it's used indirectly via [`InnerInit`] or [`InnerIvInit`].
pub trait InnerUser {
/// Inner type.
type Inner;
}
/// Resettable types.
pub trait Reset {
/// Reset state to its initial value.
fn reset(&mut self);
}
/// Trait which stores algorithm name constant, used in `Debug` implementations.
pub trait AlgorithmName {
/// Write algorithm name into `f`.
///
/// # Errors
/// `fmt::Result` is only intended for cases where an error occurs writing to the underlying
/// I/O stream.
fn write_alg_name(f: &mut fmt::Formatter<'_>) -> fmt::Result;
}
/// Serialize a key to a byte array.
pub trait KeyExport: KeySizeUser {
/// Serialize this key as a byte array.
fn to_bytes(&self) -> Key<Self>;
}
/// Types which can be initialized from a key.
pub trait KeyInit: KeySizeUser + Sized {
/// Create new value from fixed size key.
fn new(key: &Key<Self>) -> Self;
/// Create new value from variable size key.
///
/// # Errors
/// Returns [`InvalidLength`] in the event the length of the provided slice is not equal to
/// `<Self as KeySizeUser>::KeySize::USIZE`.
#[inline]
fn new_from_slice(key: &[u8]) -> Result<Self, InvalidLength> {
<&Key<Self>>::try_from(key)
.map(Self::new)
.map_err(|_| InvalidLength)
}
/// DEPRECATED: generate random key using the provided [`CryptoRng`].
///
/// Instead, you can now use the [`Generate`] trait directly with the [`Key`] type:
///
/// ```ignore
/// let key = Key::generate_from_rng(rng);
/// ```
#[deprecated(
since = "0.2.0",
note = "use the `Generate` trait impl on `Key` instead"
)]
#[cfg(feature = "rand_core")]
fn generate_key<R: CryptoRng>(rng: &mut R) -> Key<Self> {
Key::<Self>::generate_from_rng(rng)
}
}
/// Types which can be initialized from a key and initialization vector (nonce).
pub trait KeyIvInit: KeySizeUser + IvSizeUser + Sized {
/// Create new value from fixed length key and nonce.
fn new(key: &Key<Self>, iv: &Iv<Self>) -> Self;
/// Create new value from variable length key and nonce.
///
/// # Errors
/// Returns [`InvalidLength`] in the event that `key` and/or `iv` are not the expected length.
#[inline]
fn new_from_slices(key: &[u8], iv: &[u8]) -> Result<Self, InvalidLength> {
let key = <&Key<Self>>::try_from(key).map_err(|_| InvalidLength)?;
let iv = <&Iv<Self>>::try_from(iv).map_err(|_| InvalidLength)?;
Ok(Self::new(key, iv))
}
/// DEPRECATED: generate random key using the provided [`CryptoRng`].
///
/// Instead, you can now use the [`Generate`] trait directly with the [`Key`] type:
///
/// ```ignore
/// let key = Key::generate_from_rng(rng);
/// ```
#[deprecated(
since = "0.2.0",
note = "use the `Generate` trait impl on `Key` instead"
)]
#[cfg(feature = "rand_core")]
fn generate_key<R: CryptoRng>(rng: &mut R) -> Key<Self> {
Key::<Self>::generate_from_rng(rng)
}
/// DEPRECATED: generate random IV using the provided [`CryptoRng`].
///
/// Instead, you can now use the [`Generate`] trait directly with the [`Iv`] type:
///
/// ```ignore
/// let iv = Iv::generate_from_rng(rng);
/// ```
#[deprecated(
since = "0.2.0",
note = "use the `Generate` trait impl on `Iv` instead"
)]
#[cfg(feature = "rand_core")]
fn generate_iv<R: CryptoRng>(rng: &mut R) -> Iv<Self> {
Iv::<Self>::generate_from_rng(rng)
}
/// DEPRECATED: generate random key and IV using the provided [`CryptoRng`].
///
/// Instead, you can now use the [`Generate`] trait directly with the [`Key`] and [`Iv`] types:
///
/// ```ignore
/// let key = Key::generate_from_rng(rng);
/// let iv = Iv::generate_from_rng(rng);
/// ```
#[deprecated(
since = "0.2.0",
note = "use the `Generate` trait impls on `Key` and `Iv` instead"
)]
#[cfg(feature = "rand_core")]
fn generate_key_iv<R: CryptoRng>(rng: &mut R) -> (Key<Self>, Iv<Self>) {
let key = Key::<Self>::generate_from_rng(rng);
let iv = Iv::<Self>::generate_from_rng(rng);
(key, iv)
}
}
/// Types which can be fallibly initialized from a key.
pub trait TryKeyInit: KeySizeUser + Sized {
/// Create new value from a fixed-size key.
///
/// # Errors
/// If the key is considered invalid according to rules specific to the implementing type.
fn new(key: &Key<Self>) -> Result<Self, InvalidKey>;
/// Create new value from a variable size key.
///
/// # Errors
/// If the key is considered invalid according to rules specific to the implementing type.
#[inline]
fn new_from_slice(key: &[u8]) -> Result<Self, InvalidKey> {
<&Key<Self>>::try_from(key)
.map_err(|_| InvalidKey)
.and_then(Self::new)
}
}
/// Types which can be initialized from another type (usually block ciphers).
///
/// Usually used for initializing types from block ciphers.
pub trait InnerInit: InnerUser + Sized {
/// Initialize value from the `inner`.
fn inner_init(inner: Self::Inner) -> Self;
}
/// Types which can be initialized from another type and additional initialization
/// vector/nonce.
///
/// Usually used for initializing types from block ciphers.
pub trait InnerIvInit: InnerUser + IvSizeUser + Sized {
/// Initialize value using `inner` and `iv` array.
fn inner_iv_init(inner: Self::Inner, iv: &Iv<Self>) -> Self;
/// Initialize value using `inner` and `iv` slice.
///
/// # Errors
/// Returns [`InvalidLength`] in the event that `iv` is not the expected length.
#[inline]
fn inner_iv_slice_init(inner: Self::Inner, iv: &[u8]) -> Result<Self, InvalidLength> {
let iv = <&Iv<Self>>::try_from(iv).map_err(|_| InvalidLength)?;
Ok(Self::inner_iv_init(inner, iv))
}
}
/// Trait for loading current IV state.
pub trait IvState: IvSizeUser {
/// Returns current IV state.
fn iv_state(&self) -> Iv<Self>;
}
/// Trait for setting current IV state.
// TODO: merge with `IvState` in the next breaking release
pub trait SetIvState: IvState {
/// Set IV.
fn set_iv(&mut self, iv: &Iv<Self>);
/// Execute the `f` closure with the current state and reset it back
/// to the original state before the method returns.
fn peek<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
let iv = self.iv_state();
let res = f(self);
self.set_iv(&iv);
res
}
}
impl<T> KeySizeUser for T
where
T: InnerUser,
T::Inner: KeySizeUser,
{
type KeySize = <T::Inner as KeySizeUser>::KeySize;
}
impl<T> KeyIvInit for T
where
T: InnerIvInit,
T::Inner: KeyInit,
{
#[inline]
fn new(key: &Key<Self>, iv: &Iv<Self>) -> Self {
Self::inner_iv_init(T::Inner::new(key), iv)
}
#[inline]
fn new_from_slices(key: &[u8], iv: &[u8]) -> Result<Self, InvalidLength> {
T::Inner::new_from_slice(key).and_then(|i| T::inner_iv_slice_init(i, iv))
}
}
impl<T> KeyInit for T
where
T: InnerInit,
T::Inner: KeyInit,
{
#[inline]
fn new(key: &Key<Self>) -> Self {
Self::inner_init(T::Inner::new(key))
}
#[inline]
fn new_from_slice(key: &[u8]) -> Result<Self, InvalidLength> {
T::Inner::new_from_slice(key)
.map_err(|_| InvalidLength)
.map(Self::inner_init)
}
}
/// Error type for [`TryKeyInit`] for cases where the provided bytes do not correspond to a
/// valid key.
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub struct InvalidKey;
impl fmt::Display for InvalidKey {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
f.write_str("InvalidKey")
}
}
impl core::error::Error for InvalidKey {}
/// The error type returned when key and/or IV used in the [`KeyInit`],
/// [`KeyIvInit`], and [`InnerIvInit`] slice-based methods had
/// an invalid length.
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub struct InvalidLength;
impl fmt::Display for InvalidLength {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
f.write_str("Invalid Length")
}
}
impl core::error::Error for InvalidLength {}