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

Add ANSI-X9.63-KDF #102

Merged
merged 17 commits into from
Oct 14, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
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
11 changes: 10 additions & 1 deletion Cargo.lock

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

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
resolver = "2"
members = [
"hkdf",
"concat-kdf",
"concat-kdf", "ansi-x963-kdf",
]

[profile.dev]
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ Collection of [Key Derivation Functions][KDF] (KDF) written in pure Rust.
|--------------|----------------|:---------------------------------------------------------------------------------------------------:|:------------------------------------------------------------------------------------:|:-----------------------:|
| [HKDF] | [`hkdf`] | [![crates.io](https://img.shields.io/crates/v/hkdf.svg)](https://crates.io/crates/hkdf) | [![Documentation](https://docs.rs/hkdf/badge.svg)](https://docs.rs/hkdf) | ![MSRV 1.41][msrv-1.72] |
| [Concat-KDF] | [`concat-kdf`] | [![crates.io](https://img.shields.io/crates/v/concat-kdf.svg)](https://crates.io/crates/concat-kdf) | [![Documentation](https://docs.rs/concat-kdf/badge.svg)](https://docs.rs/concat-kdf) | ![MSRV 1.56][msrv-1.72] |
| [ANSI-X9.63-KDF] | [`ansi-x963-kdf`] | [![crates.io](https://img.shields.io/crates/v/ansi-x963-kdf.svg)](https://crates.io/crates/ansi-x963-kdf) | [![Documentation](https://docs.rs/ansi-x963-kdf/badge.svg)](https://docs.rs/ansi-x963-kdf) | ![MSRV 1.56][msrv-1.72] |

*NOTE: for password-based KDFs (e.g. Argon2, PBKDF2, scrypt), please see [RustCrypto/password-hashes]*

Expand Down Expand Up @@ -43,10 +44,12 @@ Unless you explicitly state otherwise, any contribution intentionally submitted

[`hkdf`]: ./hkdf
[`concat-kdf`]: ./concat-kdf
[`ansi-x963-kdf`]: ./ansi-x963-kdf

[//]: # (algorithms)

[KDF]: https://en.wikipedia.org/wiki/Key_derivation_function
[HKDF]: https://en.wikipedia.org/wiki/HKDF
[Concat-KDF]: https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-56ar.pdf
[ANSI-X9.63-KDF]: https://www.secg.org/sec1-v2.pdf
[RustCrypto/password-hashes]: https://github.com/RustCrypto/password-hashes
8 changes: 8 additions & 0 deletions ansi-x963-kdf/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Changelog
All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## 0.1.0 (2024-04-10)
- Initial release
28 changes: 28 additions & 0 deletions ansi-x963-kdf/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
[package]
name = "ansi-x963-kdf"
version = "0.1.0"
description = "ANSI X9.63 Key Derivation Function (ANSI-X9.63-KDF)"
authors = ["RustCrypto Developers"]
license = "MIT OR Apache-2.0"
readme = "README.md"
edition = "2021"
documentation = "https://docs.rs/ansi-x963-kdf"
repository = "https://github.com/RustCrypto/KDFs"
keywords = ["crypto", "ansi-x963-kdf", "KDF", "SEC1"]
categories = ["cryptography", "no-std"]
rust-version = "1.72"

[dependencies]
digest = "=0.11.0-pre.9"

[dev-dependencies]
hex-literal = "0.4"
sha2 = { version = "=0.11.0-pre.4", default-features = false }

[features]
std = []

[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]

59 changes: 59 additions & 0 deletions ansi-x963-kdf/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# RustCrypto: ANSI X9.63 Key Derivation Function (ANSI-X9.63-KDF)

[![crate][crate-image]][crate-link]
[![Docs][docs-image]][docs-link]
![Apache2/MIT licensed][license-image]
![Rust Version][rustc-image]
[![Project Chat][chat-image]][chat-link]
[![Build Status][build-image]][build-link]

Pure Rust implementation of the ANSI X9.63 Key Derivation Function (ANSI-X9.63-KDF) generic over hash function.
This function is described in the section 3.6.1 of [SEC 1: Elliptic Curve Cryptography](http://www.secg.org/sec1-v2.pdf).

# Usage

The most common way to use ANSI-X9.63-KDF is as follows: you generate a shared secret with other party (e.g. via Diffie-Hellman algorithm)
and use key derivation function to derive a shared key.

```rust
let mut key = [0u8; 32];
ansi_x963_kdf::derive_key_into::<sha2::Sha256>(b"shared-secret", b"other-info", &mut key).unwrap();
```

## Minimum Supported Rust Version

Rust **1.72** or higher.

Minimum supported Rust version can be changed in the future, but it will be
done with a minor version bump.

## SemVer Policy

- All on-by-default features of this library are covered by SemVer
- MSRV is considered exempt from SemVer as noted above

## License

Licensed under either of:

* [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0)
* [MIT license](http://opensource.org/licenses/MIT)

at your option.

### Contribution

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.

[crate-image]: https://img.shields.io/crates/v/ansi-x963-kdf.svg
[crate-link]: https://crates.io/crates/ansi-x963-kdf
[docs-image]: https://docs.rs/ansi-x963-kdf/badge.svg
[docs-link]: https://docs.rs/ansi-x963-kdf/
[license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg
[rustc-image]: https://img.shields.io/badge/rustc-1.72+-blue.svg
[chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg
[chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/260043-KDFs
[build-image]: https://github.com/RustCrypto/KDFs/workflows/ansi-x963-kdf/badge.svg?branch=master&event=push
[build-link]: https://github.com/RustCrypto/KDFs/actions?query=workflow:ansi-x963-kdf
121 changes: 121 additions & 0 deletions ansi-x963-kdf/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
//! An implementation of ANSI-X9.63 KDF Key Derivation Function.
//!
//! This function is described in the section 3.6.1 of [SEC 1: Elliptic Curve Cryptography][1].
//!
//! # Usage
//!
//! The most common way to use ANSI-X9.63 KDF is as follows: you generate a shared secret
//! with other party (e.g. via Diffie-Hellman algorithm) and use key derivation function
//! to derive a shared key.
//!
//! ```rust
//! let mut key = [0u8; 32];
//! ansi_x963_kdf::derive_key_into::<sha2::Sha256>(b"shared-secret", b"other-info", &mut key).unwrap();
//! ```
//!
//! [1]: https://www.secg.org/sec1-v2.pdf

#![no_std]
#![cfg_attr(docsrs, feature(doc_cfg))]
newpavlov marked this conversation as resolved.
Show resolved Hide resolved

use core::fmt;
use digest::{array::typenum::Unsigned, Digest, FixedOutputReset, Update};

#[cfg(feature = "std")]
extern crate std;

/// ANSI-X9.63 KDF errors.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Error {
/// The length of the secret is zero.
NoSecret,
/// The length of the output is zero.
NoOutput,
/// The length of the input is too big
InputOverflow,
/// The length of the output is too big.
CounterOverflow,
}

impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
f.write_str(match self {
Error::NoSecret => "Buffer for secret has zero length.",
Error::NoOutput => "Buffer for key has zero length.",
Error::InputOverflow => "Input length is to big.",
Error::CounterOverflow => "Requested key length is to big.",
})
}
}

#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
impl ::std::error::Error for Error {}
newpavlov marked this conversation as resolved.
Show resolved Hide resolved

/// Derives `key` in-place from `secret` and `shared_info`.
/// ```rust
/// let mut key = [0u8; 42];
/// ansi_x963_kdf::derive_key_into::<sha2::Sha256>(b"top-secret", b"info", &mut key).unwrap();
/// ```
newpavlov marked this conversation as resolved.
Show resolved Hide resolved
pub fn derive_key_into<D>(secret: &[u8], shared_info: &[u8], key: &mut [u8]) -> Result<(), Error>
where
D: Digest + FixedOutputReset,
{
if secret.is_empty() {
return Err(Error::NoSecret);
}

if key.is_empty() {
return Err(Error::NoOutput);
}

// 1. Check if |Z| + |SharedInfo| + 4 >= hashmaxlen
if secret.len() + shared_info.len() + 4 >= D::OutputSize::USIZE * (u32::MAX as usize) {
newpavlov marked this conversation as resolved.
Show resolved Hide resolved
return Err(Error::InputOverflow);
}

// Counter overflow is possible only on architectures with usize bigger than 4 bytes.
const OVERFLOW_IS_POSSIBLE: bool = core::mem::size_of::<usize>() > 4;

// 2. Check that keydatalen < hashlen × (2^32 − 1)
if OVERFLOW_IS_POSSIBLE && (key.len() >= D::OutputSize::USIZE * (u32::MAX as usize)) {
newpavlov marked this conversation as resolved.
Show resolved Hide resolved
return Err(Error::CounterOverflow);
}

let mut digest = D::new();

// 3. Initiate a 4 octet, big-endian octet string Counter as 00000001
let mut counter: u32 = 1;

// 4. For i = 1 to keydatalen/hashlen,
for chunk in key.chunks_mut(D::OutputSize::USIZE) {
// 4.1 Compute Ki = Hash(Z ‖ Counter ‖ [SharedInfo]) using the selected hash function
Update::update(&mut digest, secret);
newpavlov marked this conversation as resolved.
Show resolved Hide resolved
Update::update(&mut digest, &counter.to_be_bytes());
Update::update(&mut digest, shared_info);
chunk.copy_from_slice(&digest.finalize_reset()[..chunk.len()]);
// 4.2. Increment Counter
counter += 1;
}

Ok(())
}

/// Derives and returns `length` bytes key from `secret` and `shared_info`.
/// ```rust
/// let key = ansi_x963_kdf::derive_key::<sha2::Sha256>(b"top-secret", b"info", 42).unwrap();
/// ```
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
pub fn derive_key<D>(
secret: &[u8],
shared_info: &[u8],
length: usize,
) -> Result<std::vec::Vec<u8>, Error>
where
D: Digest + FixedOutputReset,
{
let mut key = std::vec![0u8; length];
derive_key_into::<D>(secret, shared_info, &mut key)?;
Ok(key)
}
Loading