Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .clippy.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
allow-unwrap-in-consts = true
allow-unwrap-in-tests = true
40 changes: 40 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,43 @@ members = [

[profile.dev]
opt-level = 2

[workspace.lints.clippy]
borrow_as_ptr = "warn"
cast_lossless = "warn"
cast_possible_truncation = "warn"
cast_possible_wrap = "warn"
cast_precision_loss = "warn"
cast_sign_loss = "warn"
checked_conversions = "warn"
doc_markdown = "warn"
from_iter_instead_of_collect = "warn"
implicit_saturating_sub = "warn"
manual_assert = "warn"
map_unwrap_or = "warn"
missing_errors_doc = "warn"
missing_panics_doc = "warn"
mod_module_files = "warn"
must_use_candidate = "warn"
needless_range_loop = "allow"
ptr_as_ptr = "warn"
redundant_closure_for_method_calls = "warn"
ref_as_ptr = "warn"
return_self_not_must_use = "warn"
semicolon_if_nothing_returned = "warn"
trivially_copy_pass_by_ref = "warn"
std_instead_of_alloc = "warn"
std_instead_of_core = "warn"
undocumented_unsafe_blocks = "warn"
unnecessary_safety_comment = "warn"
unwrap_used = "warn"

[workspace.lints.rust]
missing_copy_implementations = "warn"
missing_debug_implementations = "warn"
missing_docs = "warn"
trivial_casts = "warn"
trivial_numeric_casts = "warn"
unsafe_code = "forbid"
unused_lifetimes = "warn"
unused_qualifications = "warn"
3 changes: 3 additions & 0 deletions ansi-x963-kdf/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,6 @@ digest = "0.11"
[dev-dependencies]
hex-literal = "1"
sha2 = { version = "0.11", default-features = false }

[lints]
workspace = true
8 changes: 7 additions & 1 deletion ansi-x963-kdf/README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# RustCrypto: ANSI X9.63 Key Derivation Function
# [RustCrypto]: ANSI X9.63 Key Derivation Function

[![crate][crate-image]][crate-link]
[![Docs][docs-image]][docs-link]
Expand Down Expand Up @@ -39,6 +39,8 @@ Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
dual licensed as above, without any additional terms or conditions.

[//]: # (badges)

[crate-image]: https://img.shields.io/crates/v/ansi-x963-kdf.svg?logo=rust
[crate-link]: https://crates.io/crates/ansi-x963-kdf
[docs-image]: https://docs.rs/ansi-x963-kdf/badge.svg
Expand All @@ -49,3 +51,7 @@ dual licensed as above, without any additional terms or conditions.
[rustc-image]: https://img.shields.io/badge/rustc-1.85+-blue.svg
[chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg
[chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/260043-KDFs

[//]: # (links)

[RustCrypto]: https://github.com/RustCrypto
11 changes: 7 additions & 4 deletions ansi-x963-kdf/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg"
)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![forbid(unsafe_code)]
#![warn(missing_docs)]

use core::fmt;
use digest::{Digest, FixedOutputReset, array::typenum::Unsigned};
Expand All @@ -22,6 +20,10 @@ use digest::{Digest, FixedOutputReset, array::typenum::Unsigned};
/// ansi_x963_kdf::derive_key_into::<Sha256>(b"secret", b"shared-info", &mut key).unwrap();
/// assert_eq!(key, hex!("8dbb1d50bcc7fc782abc9db5c64a2826"));
/// ```
///
/// # Errors
/// - Returns [`Error::InputOverflow`] if too much input is provided
/// - Returns [`Error::CounterOverflow`] if `key` is too long
#[inline]
pub fn derive_key_into<D>(secret: &[u8], shared_info: &[u8], key: &mut [u8]) -> Result<(), Error>
where
Expand All @@ -38,13 +40,14 @@ where
// 1. Check that |Z| + |SharedInfo| + 4 < hashmaxlen
// where "hashmaxlen denote the maximum length in octets of messages that can be hashed using Hash".
// N.B.: `D::OutputSize::U64 * (u32::MAX as u64)`` is currently used as an approximation of hashmaxlen.
if secret.len() as u64 + shared_info.len() as u64 + 4 >= D::OutputSize::U64 * (u32::MAX as u64)
if secret.len() as u64 + shared_info.len() as u64 + 4
>= D::OutputSize::U64 * u64::from(u32::MAX)
{
return Err(Error::InputOverflow);
}

// 2. Check that keydatalen < hashlen × (2^32 − 1)
if key.len() as u64 >= D::OutputSize::U64 * (u32::MAX as u64) {
if key.len() as u64 >= D::OutputSize::U64 * u64::from(u32::MAX) {
return Err(Error::CounterOverflow);
}

Expand Down
2 changes: 2 additions & 0 deletions ansi-x963-kdf/tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
//! KDF2 implementation [KDF2BytesGenerator][1]
//!
//! [1]: https://downloads.bouncycastle.org/java/docs/bcprov-jdk18on-javadoc/
#![allow(clippy::unwrap_used, reason = "tests")]
Comment thread
tarcieri marked this conversation as resolved.

use digest::{Digest, FixedOutputReset};
use hex_literal::hex;
use sha2::{Sha224, Sha256, Sha512};
Expand Down
3 changes: 3 additions & 0 deletions bake-kdf/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,8 @@ belt-hash = { version = "0.2.0-rc.5", default-features = false }
[dev-dependencies]
hex-literal = "1"

[lints]
workspace = true

[package.metadata.docs.rs]
all-features = true
6 changes: 5 additions & 1 deletion bake-kdf/README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# RustCrypto: bake-kdf
# [RustCrypto]: bake-kdf

[![crate][crate-image]][crate-link]
[![Docs][docs-image]][docs-link]
Expand Down Expand Up @@ -53,3 +53,7 @@ dual licensed as above, without any additional terms or conditions.
[rustc-image]: https://img.shields.io/badge/rustc-1.85+-blue.svg
[chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg
[chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/260043-KDFs

[//]: # (links)

[RustCrypto]: https://github.com/RustCrypto
31 changes: 25 additions & 6 deletions bake-kdf/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@
html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg"
)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![forbid(unsafe_code)]
#![warn(missing_docs)]
#![allow(clippy::unwrap_used, reason = "todo")]

use belt_hash::digest::FixedOutput;
use belt_hash::{BeltHash, Digest, block_api::belt_compress};
Expand All @@ -15,9 +14,13 @@ use belt_hash::{BeltHash, Digest, block_api::belt_compress};
///
/// # Panics
/// If `N` is not equal to 16, 24, or 32.
// TODO: use compile-time checks for `N`
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Went ahead and implemented the compile-time checks here and below in belt_keyrep

#[inline]
#[must_use]
pub fn belt_keyexpand<const N: usize>(k: &[u8; N]) -> [u32; 8] {
const {
assert!(matches!(N, 16 | 24 | 32), "N must be 16, 24, or 32");
}

let mut t = [0u32; 8];
// TODO: move this conversion into `belt_keyrep` when we will be able
// to use generic parameters as `[u32; N / 4]`.
Expand All @@ -44,15 +47,30 @@ pub fn belt_keyexpand<const N: usize>(k: &[u8; N]) -> [u32; 8] {
/// `belt-keyrep` key repetition algorithm described in STB 34.101.31-2020 8.1.3.
///
/// # Panics
/// If `(N, M)` is not equal to `(16, 16)`, `(24, 16)`, `(24, 24)`,
/// `(32, 16)`, `(32, 24)`, or `(32, 32)`.
// TODO: use compile-time check for `N` and `M`
/// If `(N, M)` is not equal to one of:
/// - `(16, 16)`
/// - `(24, 16)`
/// - `(24, 24)`
/// - `(32, 16)`
/// - `(32, 24)`
/// - `(32, 32)`
#[inline]
#[must_use]
pub fn belt_keyrep<const N: usize, const M: usize>(
x: &[u8; N],
d: &[u8; 12],
i: &[u8; 16],
) -> [u8; M] {
const {
assert!(
matches!(
(N, M),
(16, 16) | (24, 16) | (24, 24) | (32, 16) | (32, 24) | (32, 32)
),
"invalid N/M values"
);
}

let r: u32 = match (N, M) {
(16, 16) => 0xC8BA94B1,
(24, 16) => 0x12D6E35B,
Expand Down Expand Up @@ -89,6 +107,7 @@ pub fn belt_keyrep<const N: usize, const M: usize>(

/// `bake-kdf` key derivation algorithm described in STB 34.101.66-2014 8.1.4.
#[inline]
#[must_use]
pub fn bake_kdf(x: &[u8], s: &[u8], c: u128) -> [u8; 32] {
let mut hasher = BeltHash::default();
hasher.update(x);
Expand Down
2 changes: 2 additions & 0 deletions bake-kdf/tests/tests.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
//! Test vectors

use bake_kdf::{bake_kdf, belt_keyexpand, belt_keyrep};
use hex_literal::hex;

Expand Down
3 changes: 3 additions & 0 deletions hkdf/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,8 @@ hex-literal = "1"
sha1 = { version = "0.11", default-features = false }
sha2 = { version = "0.11", default-features = false }

[lints]
workspace = true

[package.metadata.docs.rs]
all-features = true
6 changes: 5 additions & 1 deletion hkdf/README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# RustCrypto: HKDF
# [RustCrypto]: HKDF

[![crate][crate-image]][crate-link]
[![Docs][docs-image]][docs-link]
Expand Down Expand Up @@ -112,3 +112,7 @@ dual licensed as above, without any additional terms or conditions.
[chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/260043-KDFs
[build-image]: https://github.com/RustCrypto/KDFs/workflows/hkdf/badge.svg?branch=master&event=push
[build-link]: https://github.com/RustCrypto/KDFs/actions?query=workflow:hkdf

[//]: # (links)

[RustCrypto]: https://github.com/RustCrypto
2 changes: 1 addition & 1 deletion hkdf/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ impl fmt::Display for InvalidPrkLength {

impl core::error::Error for InvalidPrkLength {}

/// Structure for InvalidLength, used for output error handling.
/// Structure for `InvalidLength`, used for output error handling.
#[derive(Copy, Clone, Debug)]
pub struct InvalidLength;

Expand Down
20 changes: 16 additions & 4 deletions hkdf/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg"
)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![forbid(unsafe_code)]
#![warn(missing_docs)]

use hmac::{
Hmac, SimpleHmac,
Expand Down Expand Up @@ -44,6 +42,7 @@ pub struct GenericHkdfExtract<H: HmacImpl> {

impl<H: HmacImpl> GenericHkdfExtract<H> {
/// Initiates the HKDF-Extract context with the given optional salt
#[must_use]
pub fn new(salt: Option<&[u8]>) -> Self {
let default_salt = Output::<H>::default();
let salt = salt.unwrap_or(&default_salt);
Expand All @@ -58,6 +57,7 @@ impl<H: HmacImpl> GenericHkdfExtract<H> {

/// Completes the HKDF-Extract operation, returning both the generated pseudorandom key and
/// `Hkdf` struct for expanding.
#[allow(clippy::missing_panics_doc, reason = "PRK size is correct")]
pub fn finalize(self) -> (Output<H>, GenericHkdf<H>) {
let prk = self.hmac.finalize();
let hkdf = GenericHkdf::<H>::from_prk(&prk).expect("PRK size is correct");
Expand Down Expand Up @@ -90,13 +90,17 @@ impl<H: HmacImpl> GenericHkdf<H> {
/// Convenience method for [`extract`][Hkdf::extract] when the generated
/// pseudorandom key can be ignored and only HKDF-Expand operation is needed. This is the most
/// common constructor.
#[must_use]
pub fn new(salt: Option<&[u8]>, ikm: &[u8]) -> Self {
let (_, hkdf) = Self::extract(salt, ikm);
hkdf
}

/// Create `Hkdf` from an already cryptographically strong pseudorandom key
/// as per section 3.3 from RFC5869.
///
/// # Errors
/// Returns [`InvalidPrkLength`] if `prk` is shorter than the output size of `H`.
pub fn from_prk(prk: &[u8]) -> Result<Self, InvalidPrkLength> {
// section 2.3 specifies that `prk` must be "at least HashLen octets"
let hash_len = <H as OutputSizeUser>::OutputSize::to_usize();
Expand All @@ -109,6 +113,7 @@ impl<H: HmacImpl> GenericHkdf<H> {

/// The RFC5869 HKDF-Extract operation returning both the generated
/// pseudorandom key and `Hkdf` struct for expanding.
#[must_use]
pub fn extract(salt: Option<&[u8]>, ikm: &[u8]) -> (Output<H>, Self) {
let mut extract_ctx = GenericHkdfExtract::<H>::new(salt);
extract_ctx.input_ikm(ikm);
Expand All @@ -118,6 +123,10 @@ impl<H: HmacImpl> GenericHkdf<H> {
/// The RFC5869 HKDF-Expand operation. This is equivalent to calling
/// [`expand`][Hkdf::extract] with the `info` argument set equal to the
/// concatenation of all the elements of `info_components`.
///
/// # Errors
/// Returns [`InvalidLength`] in the event `okm` is too large.
#[allow(clippy::missing_panics_doc, reason = "expect should not fail")]
pub fn expand_multi_info(
&self,
info_components: &[&[u8]],
Expand All @@ -134,7 +143,7 @@ impl<H: HmacImpl> GenericHkdf<H> {
let mut hmac = self.hmac.clone();

if let Some(ref prev) = prev {
hmac.update(prev)
hmac.update(prev);
};

// Feed in the info components in sequence. This is equivalent to feeding in the
Expand All @@ -143,7 +152,7 @@ impl<H: HmacImpl> GenericHkdf<H> {
hmac.update(info);
}

hmac.update(&[block_n as u8 + 1]);
hmac.update(&[u8::try_from(block_n).expect("should convert") + 1]);

let output = hmac.finalize();

Expand All @@ -159,6 +168,9 @@ impl<H: HmacImpl> GenericHkdf<H> {
/// The RFC5869 HKDF-Expand operation
///
/// If you don't have any `info` to pass, use an empty slice.
///
/// # Errors
/// Returns [`InvalidLength`] in the event `okm` is too large.
pub fn expand(&self, info: &[u8], okm: &mut [u8]) -> Result<(), InvalidLength> {
self.expand_multi_info(&[info], okm)
}
Expand Down
4 changes: 3 additions & 1 deletion hkdf/tests/rfc5869.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
//! Test vectors from https://tools.ietf.org/html/rfc5869
//! Test vectors from <https://tools.ietf.org/html/rfc5869>.
#![allow(clippy::unwrap_used, reason = "tests")]

use hkdf::{GenericHkdf, HmacImpl};
use hmac::{Hmac, SimpleHmac};

Expand Down
4 changes: 3 additions & 1 deletion hkdf/tests/tests.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
//! Integration tests.

use core::iter;

use hex_literal::hex;
Expand Down Expand Up @@ -184,7 +186,7 @@ fn test_extract_streaming() {

#[test]
fn test_debug_impls() {
fn needs_debug<T: std::fmt::Debug>() {}
fn needs_debug<T: core::fmt::Debug>() {}
needs_debug::<Hkdf<Sha256>>();
needs_debug::<HkdfExtract<Sha256>>();
}
2 changes: 2 additions & 0 deletions hkdf/tests/wycheproof.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
//! Wycheproof test vectors.

use hkdf::{GenericHkdf, HmacImpl};
use hmac::{Hmac, SimpleHmac};

Expand Down
3 changes: 3 additions & 0 deletions kbkdf/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,8 @@ sha1 = { version = "0.11", default-features = false }
cmac = "0.8.0-rc.4"
aes = "0.9.0-rc.4"

[lints]
workspace = true

[package.metadata.docs.rs]
all-features = true
Loading
Loading