Skip to content

Commit

Permalink
x
Browse files Browse the repository at this point in the history
Signed-off-by: Eric Lagergren <[email protected]>
  • Loading branch information
elagergren-spideroak committed Jan 27, 2025
1 parent 93aae41 commit 0ebda8d
Show file tree
Hide file tree
Showing 23 changed files with 481 additions and 290 deletions.
21 changes: 21 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions crates/crypto/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ std = [
"sha3-utils/std",
"spin?/std",
"subtle/std",
"thiserror/std",
"zeroize/std",
]

Expand Down Expand Up @@ -175,6 +176,7 @@ sha2 = { version = "0.10", default-features = false }
sha3-utils = { version = "0.3.0", default-features = false }
spin = { workspace = true, default-features = false, features = ["mutex", "once", "spin_mutex"], optional = true }
subtle = { version = "2.5", default-features = false, features = ["core_hint_black_box"] }
thiserror = { version = "2", default-features = false }
typenum = { version = "1", default-features = false, features = ["const-generics"] }
# Only pulled into non-dev builds if `test_util` is enabled. It
# won't bloat release builds, though, since users of this crate
Expand Down
15 changes: 9 additions & 6 deletions crates/crypto/src/aead.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ pub use crate::hpke::AeadId;
use crate::{
csprng::{Csprng, Random},
kdf::{Expand, Kdf, KdfError, Prk},
keys::{raw_key, SecretKey, SecretKeyBytes},
keys::{raw_key, FixedLength, SecretKey, SecretKeyBytes},
util::const_assert,
zeroize::Zeroize,
};
Expand Down Expand Up @@ -410,7 +410,7 @@ pub trait Aead {
};

/// The key used by the [`Aead`].
type Key: SecretKey<Size = Self::KeySize>;
type Key: SecretKey + FixedLength<Size = Self::KeySize>;

/// Creates a new [`Aead`].
fn new(key: &Self::Key) -> Self;
Expand Down Expand Up @@ -539,7 +539,7 @@ pub trait Aead {

/// Shorthand which the compiler does not understand without
/// a good amount of hand holding.
pub type KeyData<A> = SecretKeyBytes<<<A as Aead>::Key as SecretKey>::Size>;
pub type KeyData<A> = SecretKeyBytes<<<A as Aead>::Key as FixedLength>::Size>;

/// An authentication tag.
pub type Tag<A> = GenericArray<u8, <A as Aead>::Overhead>;
Expand Down Expand Up @@ -1347,15 +1347,18 @@ mod committing {
// The nonce length is fixed, so use
// HMAC(K || N || A)[1 : k] per Theorem 3.2.
let tag = {
let key = $crate::keys::SecretKey::try_export_secret(&self.key)?;
let mut hmac = $crate::hmac::Hmac::<$hash>::new(key.as_bytes());
let bytes = $crate::keys::SecretKey::try_export_secret(&self.key)?;
let key = $crate::hmac::HmacKey::<$hash>::new(
$crate::keys::RawSecretBytes::raw_secret_bytes(&bytes),
);
let mut hmac = $crate::hmac::Hmac::<$hash>::new(&key);
hmac.update(nonce);
hmac.update(ad);
hmac.tag()
};
let mut key_bytes = $crate::generic_array::GenericArray::<
u8,
<<$inner as $crate::aead::Aead>::Key as $crate::keys::SecretKey>::Size,
<<$inner as $crate::aead::Aead>::Key as $crate::keys::FixedLength>::Size,
>::default();
let k = ::core::cmp::min(tag.len(), key_bytes.as_slice().len());
key_bytes
Expand Down
62 changes: 38 additions & 24 deletions crates/crypto/src/bearssl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,16 @@ use crate::{
Lifetime, OpenError, SealError,
},
asn1::{max_sig_len, raw_sig_len, RawSig, Sig},
csprng::Csprng,
block::BlockSize,
csprng::{Csprng, Random},
ec::{Curve, Curve25519, Scalar, Secp256r1, Secp384r1, Secp521r1, Uncompressed},
hash::{Block, Digest, Hash, HashId},
hash::{Digest, Hash, HashId},
hex::ToHex,
hkdf::hkdf_impl,
hmac::hmac_impl,
import::{ExportError, Import, ImportError},
kem::{dhkem_impl, DecapKey, Ecdh, EcdhError, EncapKey, SharedSecret},
keys::{PublicKey, SecretKey, SecretKeyBytes},
keys::{FixedLength, PublicKey, SecretKey, SecretKeyBytes},
signer::{PkError, Signer, SignerError, SignerId, SigningKey, VerifyingKey},
zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing},
};
Expand Down Expand Up @@ -403,7 +404,20 @@ macro_rules! ecdh_impl {
}

impl SecretKey for $sk {
fn new<R: Csprng>(rng: &mut R) -> Self {
type Secret = SecretKeyBytes<<$curve as Curve>::ScalarSize>;

#[inline]
fn try_export_secret(&self) -> Result<Self::Secret, ExportError> {
Ok(SecretKeyBytes::new(self.kbuf.0.into()))
}
}

impl FixedLength for $sk {
type Size = <$curve as Curve>::ScalarSize;
}

impl Random for $sk {
fn random<R: Csprng>(rng: &mut R) -> Self {
// We don't know what `rng` is, so construct our
// own.
let mut rng = RngWrapper::new(rng);
Expand Down Expand Up @@ -436,13 +450,6 @@ macro_rules! ecdh_impl {
}
Self { kbuf }
}

type Size = <$curve as Curve>::ScalarSize;

#[inline]
fn try_export_secret(&self) -> Result<SecretKeyBytes<Self::Size>, ExportError> {
Ok(SecretKeyBytes::new(self.kbuf.0.into()))
}
}

impl ConstantTimeEq for $sk {
Expand All @@ -458,10 +465,10 @@ macro_rules! ecdh_impl {
}
}

impl Import<SecretKeyBytes<<Self as SecretKey>::Size>> for $sk {
impl Import<SecretKeyBytes<<Self as FixedLength>::Size>> for $sk {
#[inline]
fn import(
data: SecretKeyBytes<<Self as SecretKey>::Size>,
data: SecretKeyBytes<<Self as FixedLength>::Size>,
) -> Result<Self, ImportError> {
Self::import(data.as_bytes())
}
Expand Down Expand Up @@ -703,8 +710,21 @@ macro_rules! ecdsa_impl {
}

impl SecretKey for $sk {
type Secret = SecretKeyBytes<<$curve as Curve>::ScalarSize>;

#[inline]
fn new<R: Csprng>(rng: &mut R) -> Self {
fn try_export_secret(&self) -> Result<Self::Secret, ExportError> {
Ok(SecretKeyBytes::new(self.kbuf.0.into()))
}
}

impl FixedLength for $sk {
type Size = <$curve as Curve>::ScalarSize;
}

impl Random for $sk {
#[inline]
fn random<R: Csprng>(rng: &mut R) -> Self {
// We don't know what `rng` is, so construct our
// own.
let mut rng = RngWrapper::new(rng);
Expand Down Expand Up @@ -744,13 +764,6 @@ macro_rules! ecdsa_impl {

Self { kbuf }
}

type Size = <$curve as Curve>::ScalarSize;

#[inline]
fn try_export_secret(&self) -> Result<SecretKeyBytes<Self::Size>, ExportError> {
Ok(SecretKeyBytes::new(self.kbuf.0.into()))
}
}

#[cfg(test)]
Expand Down Expand Up @@ -973,9 +986,6 @@ macro_rules! hash_impl {
type DigestSize = U<{ $digest_size as usize }>;
const DIGEST_SIZE: usize = $digest_size as usize;

const BLOCK_SIZE: usize = $block_size;
type Block = Block<{ Self::BLOCK_SIZE }>;

#[inline]
fn new() -> Self {
let mut ctx = $ctx::default();
Expand Down Expand Up @@ -1004,6 +1014,10 @@ macro_rules! hash_impl {
out
}
}

impl BlockSize for $name {
type BlockSize = U<{ $block_size }>;
}
};
}
hash_impl!(
Expand Down
17 changes: 17 additions & 0 deletions crates/crypto/src/block.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
//! Operations on blocks.
#![forbid(unsafe_code)]

use generic_array::{ArrayLength, GenericArray};

/// Implemented by types that operate on blocks.
///
/// For example, block ciphers or the Merkle-Damgård
/// construction.
pub trait BlockSize {
/// The size in bytes of the block.
type BlockSize: ArrayLength;
}

/// A block.
pub type Block<S> = GenericArray<u8, <S as BlockSize>::BlockSize>;
30 changes: 16 additions & 14 deletions crates/crypto/src/ed25519.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@ use subtle::{Choice, ConstantTimeEq};
use typenum::U32;

use crate::{
csprng::Csprng,
csprng::{Csprng, Random},
hex::ToHex,
import::{try_import, ExportError, Import, ImportError},
keys::{PublicKey, SecretKey, SecretKeyBytes},
keys::{FixedLength, PublicKey, SecretKey, SecretKeyBytes},
signer::{self, PkError, Signer, SignerError, SignerId},
zeroize::{ZeroizeOnDrop, Zeroizing},
zeroize::ZeroizeOnDrop,
};

/// EdDSA using Ed25519.
Expand Down Expand Up @@ -68,14 +68,6 @@ impl signer::SigningKey<Ed25519> for SigningKey {
}

impl SecretKey for SigningKey {
type Size = U32;

fn new<R: Csprng>(rng: &mut R) -> Self {
let mut sk = dalek::SecretKey::default();
rng.fill_bytes(&mut sk);
Self(dalek::SigningKey::from_bytes(&sk))
}

type Secret = SecretKeyBytes<U32>;

#[inline]
Expand All @@ -84,11 +76,21 @@ impl SecretKey for SigningKey {
}
}

impl FixedLength for SigningKey {
type Size = U32;
}

impl Random for SigningKey {
fn random<R: Csprng>(rng: &mut R) -> Self {
let mut sk = dalek::SecretKey::default();
rng.fill_bytes(&mut sk);
Self(dalek::SigningKey::from_bytes(&sk))
}
}

impl ConstantTimeEq for SigningKey {
fn ct_eq(&self, other: &Self) -> Choice {
let lhs = Zeroizing::new(self.0.to_bytes());
let rhs = Zeroizing::new(other.0.to_bytes());
ConstantTimeEq::ct_eq(lhs.as_ref(), rhs.as_ref())
self.0.ct_eq(&other.0)
}
}

Expand Down
32 changes: 0 additions & 32 deletions crates/crypto/src/hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
#![forbid(unsafe_code)]

use core::{
borrow::{Borrow, BorrowMut},
fmt::{self, Debug},
num::NonZeroU16,
ops::{Deref, DerefMut},
Expand Down Expand Up @@ -66,12 +65,6 @@ pub trait Hash: Clone {
/// Shorthand for [`DigestSize`][Self::DigestSize].
const DIGEST_SIZE: usize = Self::DigestSize::USIZE;

/// The size in bytes of a [`Self::Block`].
const BLOCK_SIZE: usize;

/// An individual block.
type Block: Borrow<[u8]> + BorrowMut<[u8]> + Default + Clone;

/// Creates a new [`Hash`].
fn new() -> Self;

Expand Down Expand Up @@ -199,31 +192,6 @@ impl<N: ArrayLength> ConstantTimeEq for Digest<N> {
}
}

/// An hash function block.
#[derive(Clone)]
pub struct Block<const N: usize>([u8; N]);

impl<const N: usize> Default for Block<N> {
#[inline]
fn default() -> Self {
Self([0u8; N])
}
}

impl<const N: usize> Borrow<[u8]> for Block<N> {
#[inline]
fn borrow(&self) -> &[u8] {
self.0.borrow()
}
}

impl<const N: usize> BorrowMut<[u8]> for Block<N> {
#[inline]
fn borrow_mut(&mut self) -> &mut [u8] {
self.0.borrow_mut()
}
}

/// A cryptographic hash over a set of strings such that each
/// element is unambiguously encoded per [NIST SP 800-185].
///
Expand Down
Loading

0 comments on commit 0ebda8d

Please sign in to comment.