Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

convert newtypes to const generics #274

Draft
wants to merge 26 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
e5e45c0
convert blake2b::Digest to const generics
Feb 3, 2022
fb394f4
simplified and documented const generics impls
Feb 3, 2022
7c71df1
remove duplicate docs on PublicVec
Feb 3, 2022
d950d04
move to marker types and traits
Feb 4, 2022
4835b7c
Merge branch 'master' into const-generics
Feb 4, 2022
52582f9
squash me
Feb 13, 2022
1a4b509
split Data into PublicData and SecretData
Apr 3, 2022
651e7a6
remove optional bounds and fix some cfgs
Apr 3, 2022
26143d7
move/fix docs, remove unnecessary lifetimes
Apr 3, 2022
0ce38c5
broaden PartialEq impls for {Secret,Public}Data
Apr 3, 2022
f622c92
base: better module docs
Apr 3, 2022
64ab637
rename to ArrayVecData and add actual ArrayData
Apr 3, 2022
6930a0f
rename PublicData and SecretData to Public and Secret
Apr 30, 2022
f45f7ec
change blake2b Digest to use ArrayVecData
Apr 30, 2022
cae31f7
restrict PartialEq to exact same type
Apr 30, 2022
e79316c
fix base docs line in hazardous module docs
Apr 30, 2022
a086bcf
move to core::fmt::Debug for Secret and Public
May 1, 2022
cb85630
add omitted_debug tests to base types
May 1, 2022
ee63c2a
clean up docs
May 1, 2022
68e03b9
add generate_with_size method to Public and Secret
May 1, 2022
967e0b9
simplify to Context and Data super traits
May 1, 2022
1b2a99d
begin base test_framework
May 11, 2022
025b823
remove safe_api bound on as_bytes base tests
May 11, 2022
17a7b54
add base tests for blake2b Digest
May 11, 2022
0cc1667
move per-type base test impl to macro
Jul 18, 2022
d5846af
move aead::SecretKey to const generics
Jul 18, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
180 changes: 180 additions & 0 deletions src/hazardous/base.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
use crate::errors::UnknownCryptoError;

/// This trait holds most of the behavior of types whose data are
/// meant to be public. This is what users are expected to import
/// in order to work with various Orion types that represent
/// non-secret data.
pub trait Public<D>: Sized {
/// Construct from a given byte slice.
///
/// ## Errors
/// `UnknownCryptoError` will be returned if:
/// - `slice` is empty
/// - TODO: figure out how to express max length in the docs
fn from_slice(slice: &[u8]) -> Result<Self, UnknownCryptoError>;

/// Return a byte slice representing the underlying data.
fn as_ref(&self) -> &[u8];

/// Get the length of the underlying data in bytes.
fn len(&self) -> usize {
self.as_ref().len()
}

/// Check if the length of the underlying data is 0.
fn is_empty(&self) -> bool {
self.len() == 0
}
}

/// This is a trait used to express the fact that a type can be interpreted
/// as or converted from another type. It's used primarily to let us
/// reinterpret simple wrappers over [`PublicArray`][0] as the `PublicArray`
/// itself.
///
/// [0]: crate::hazardous::base::PublicArray
pub trait Wrapper<T> {
/// This allows us to require that `Self` can return a reference to
/// the underlying `T`. It's functionally equivalent to `AsRef<T>`
fn data(&self) -> &T;

/// This allows us to require that `Self` can be constructed from
/// its underlying type without possibility of failure. It's
/// functionally equivalent to `From<T>`.
fn from(data: T) -> Self;
}

// TODO: Do we want to redefine Wrapper<T> as:
// `trait Wrapper<T>: AsRef<T> + From<T> {}` ? It seems equivalent. If
// we're going to use a macro to generate these `Wrapper` impls anyway, we
// might as well just use the standard traits (?).

/// `PublicArray` is a convenient type for storing public bytes in an array.
/// It implements [`Public`](crate::hazardous::base::Public), so creating
/// a newtype around it that also implements `Public` is fairly simple.
///
/// ```rust
/// use orion::hazardous::base::{Public, PublicArray, Wrapper};
///
/// // Create a type that must be exactly 32 bytes long (32..=32).
/// type ShaArray = PublicArray<32, 32>;
/// struct ShaDigest(ShaArray);
///
/// // Implement Wrapper (only has to be imported for newtype creation).
/// // This is the block we may want to have a macro derive for us.
/// impl Wrapper<ShaArray> for ShaDigest {
/// fn data(&self) -> &ShaArray { &self.0 }
/// fn from(data: ShaArray) -> Self { Self(data) }
/// }
///
/// // Thanks to an auto-impl, `ShaDigest` now implements `Public`.
/// let digest = ShaDigest::from_slice(&[42; 32]);
/// assert!(digest.is_ok());
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct PublicArray<const MIN: usize, const MAX: usize> {
value: [u8; MAX],
original_length: usize,
}

impl<const MIN: usize, const MAX: usize> Public<Self> for PublicArray<MIN, MAX> {
fn from_slice(slice: &[u8]) -> Result<Self, UnknownCryptoError> {
let slice_len = slice.len();

if !(MIN..=MAX).contains(&slice_len) {
return Err(UnknownCryptoError);
}

let mut value = [0u8; MAX];
value[..slice_len].copy_from_slice(slice);

Ok(Self {
value,
original_length: slice_len,
})
}

fn as_ref(&self) -> &[u8] {
self.value.get(..self.original_length).unwrap()
}
}

/// Anything that can be converted to/from a `PublicArray` will
/// implement `Public` thanks to this auto implementation. The
/// ability to be converted to/from a PublicArray is expressed
/// using the `PublicData<Data = PublicArray<_,_>` trait bound.
impl<T, const MIN: usize, const MAX: usize> Public<PublicArray<MIN, MAX>> for T
where
T: Wrapper<PublicArray<MIN, MAX>>,
{
fn from_slice(bytes: &[u8]) -> Result<Self, UnknownCryptoError> {
let a = PublicArray::from_slice(bytes)?;
Ok(Self::from(a))
}

fn as_ref(&self) -> &[u8] {
self.data().as_ref()
}
}

/// `PublicVec` is a convenient type for storing public bytes in an `Vec`.
/// It implements [`Public`](crate::hazardous::base::Public), so creating
/// a newtype around it that also implements `Public` is fairly simple.
///
/// ```rust
/// use orion::hazardous::base::{Public, PublicVec, Wrapper};
///
/// // Maybe you want your public key to be variable-sized.
/// struct PublicKey(PublicVec);
///
/// // Implement Wrapper (only has to be imported for newtype creation).
/// // This is the block we may want to have a macro derive for us.
/// impl Wrapper<PublicVec> for PublicKey {
/// fn data(&self) -> &PublicVec { &self.0 }
/// fn from(data: PublicVec) -> Self { Self(data) }
/// }
///
/// // Thanks to an auto-impl, `PublicKey` now implements `Public`.
/// let digest = PublicKey::from_slice(&[42; 32]);
/// assert!(digest.is_ok());
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct PublicVec {
value: Vec<u8>,
original_length: usize,
}

/// Anything that can be converted to/from a `PublicVec` will
/// implement `Public` thanks to this auto implementation. The
/// ability to be converted to/from a PublicAVecis expressed
/// using the `PublicDynamic<Data = PublicVec<_,_>` trait bound.
impl Public<Self> for PublicVec {
fn from_slice(slice: &[u8]) -> Result<Self, UnknownCryptoError> {
Ok(Self {
value: Vec::from(slice),
original_length: slice.len(),
})
}

fn as_ref(&self) -> &[u8] {
self.value.get(..self.original_length).unwrap()
}
}

/// Anything that can be converted to/from a `PublicVec` will
/// implement `Public` thanks to this auto implementation. The
/// ability to be converted to/from a PublicArray is expressed
/// using the `Wrapper<PublicVec>` trait bound.
impl<T> Public<PublicVec> for T
where
T: Wrapper<PublicVec>,
{
fn from_slice(bytes: &[u8]) -> Result<Self, UnknownCryptoError> {
let a = PublicVec::from_slice(bytes)?;
Ok(Self::from(a))
}

fn as_ref(&self) -> &[u8] {
self.data().as_ref()
}
}
28 changes: 20 additions & 8 deletions src/hazardous/hash/blake2/blake2b.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,17 +62,29 @@
//! [`mac::blake2b`]: crate::hazardous::mac::blake2b

use crate::errors::UnknownCryptoError;
use crate::hazardous::base::{Public, PublicArray, Wrapper};
use crate::hazardous::hash::blake2::blake2b_core;
use crate::hazardous::hash::blake2::blake2b_core::BLAKE2B_OUTSIZE;

construct_public! {
/// A type to represent the `Digest` that BLAKE2b returns.
///
/// # Errors:
/// An error will be returned if:
/// - `slice` is empty.
/// - `slice` is greater than 64 bytes.
(Digest, test_digest, 1, BLAKE2B_OUTSIZE)
type Blake2bArray = PublicArray<1, BLAKE2B_OUTSIZE>;

/// A type to represent the `Digest` that BLAKE2b returns.
///
/// # Errors:
/// An error will be returned if:
/// - `slice` is empty.
/// - `slice` is greater than 64 bytes.
#[derive(Debug, Clone, PartialEq)]
pub struct Digest(Blake2bArray);

impl Wrapper<Blake2bArray> for Digest {
fn data(&self) -> &Blake2bArray {
&self.0
}

fn from(data: Blake2bArray) -> Self {
Self(data)
}
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we choose not to use macros anywhere, we will incur this cost of extra boilerplate code for each newtype we want to add. It's not that much boilerplate, but it may add up. The simple solution here is to have a single small macro (impl_wrapper) that just does the Wrapper<T> implementation, and let the traits take care of the rest.

}

#[derive(Debug, Clone)]
Expand Down
1 change: 1 addition & 0 deletions src/hazardous/kdf/argon2i.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@
//! [`zeroize` crate]: https://crates.io/crates/zeroize

use crate::errors::UnknownCryptoError;
use crate::hazardous::base::Public;
use crate::hazardous::hash::blake2::blake2b::Blake2b;
use crate::hazardous::hash::blake2::blake2b_core::BLAKE2B_OUTSIZE;
use crate::util;
Expand Down
3 changes: 3 additions & 0 deletions src/hazardous/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,6 @@ pub mod stream;

/// Elliptic-Curve Cryptography.
pub mod ecc;

/// TODO: This probably belongs somewhere else.
pub mod base;
1 change: 1 addition & 0 deletions src/high_level/kex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ pub use crate::hazardous::ecc::x25519::PrivateKey;
pub use crate::hazardous::ecc::x25519::PublicKey;

use crate::errors::UnknownCryptoError;
use crate::hazardous::base::Public;
use crate::hazardous::ecc::x25519;
use crate::hazardous::hash::blake2::blake2b::{Blake2b, Digest};
use core::convert::TryFrom;
Expand Down
1 change: 1 addition & 0 deletions tests/hash/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ pub mod sha384_nist_cavp;
pub mod sha512_nist_cavp;

use crate::TestCaseReader;
use orion::hazardous::base::Public;
use orion::hazardous::hash::{blake2, sha2::sha256, sha2::sha384, sha2::sha512};
use orion::hazardous::mac;

Expand Down