-
Notifications
You must be signed in to change notification settings - Fork 78
Feat: Add NIST SP800-108 KDF mechanisms #257
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
Merged
wiktor-k
merged 25 commits into
parallaxsecond:main
from
jacobprudhomme:add-sp800-108-kdf
May 12, 2025
Merged
Changes from 22 commits
Commits
Show all changes
25 commits
Select commit
Hold shift + click to select a range
f0a2974
Added mechanisms for NIST SP 800-108 KDF and their parameters
jacobprudhomme 543dd75
Added derive_keys function to get additional derived keys from mechan…
jacobprudhomme 0641873
Restructured design to actually be able to reference original memory …
jacobprudhomme 799469a
Qualified all cryptoki_sys imports as a stylistic choice
jacobprudhomme 5f7a922
Simplified CounterFormat and DkmLengthFormat wrapper structs
jacobprudhomme 8258b7b
Added support for not providing additional keys to derive
jacobprudhomme d2b09c4
Fixed issue where underlying derived key structs were being formed in…
jacobprudhomme 3cb3c34
Cleaned up code with implementation of From for DerivedKey
jacobprudhomme 8ac48ed
Removed additional types to match the PKCS#11 spec 1-to-1
jacobprudhomme f1a15f7
Changed paradigm for how additional derived keys should be retrieved …
jacobprudhomme 6cd230f
Improved doc comments
jacobprudhomme 3a6d286
Improved comments and expect() error messages
jacobprudhomme 8a9a30a
Added tests for NIST SP800-108 KDF (KBKDF)
jacobprudhomme 91cd39f
Removed all cryptoki_sys qualifiers
jacobprudhomme 1d2fca8
Renamed `DkmLengthMethod` to `KbkdfDkmLengthMethod` for consistency
jacobprudhomme 4e6be13
Removed unused tests I forgot about
jacobprudhomme 56a113d
Made lint fixes
jacobprudhomme d0a7c87
Improved doc comments
jacobprudhomme 53f116f
Made spelling fix
jacobprudhomme 18de278
Changed to `NonZeroUsize` for defining bit-width of `CounterFormat` a…
jacobprudhomme e34b4b6
Split out tests for different modes of the SP800-108 KDF
jacobprudhomme bea29ba
Added mutability marker to `PhantomData` sitting inside KDF params, t…
jacobprudhomme 074c21b
Removed pinned boxes
jacobprudhomme 13f40fa
Improved safety comment on `make_mechanism()`
jacobprudhomme 5b2a843
Made formatting fixes
jacobprudhomme File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,374 @@ | ||
// Copyright 2025 Contributors to the Parsec project. | ||
// SPDX-License-Identifier: Apache-2.0 | ||
//! Mechanisms of NIST key-based key derive functions (SP 800-108, informally KBKDF) | ||
//! See: <https://docs.oasis-open.org/pkcs11/pkcs11-curr/v3.0/os/pkcs11-curr-v3.0-os.html#_Toc30061446> | ||
|
||
use core::{convert::TryInto, marker::PhantomData, pin::Pin, ptr}; | ||
use std::num::NonZeroUsize; | ||
|
||
use cryptoki_sys::{ | ||
CK_ATTRIBUTE, CK_ATTRIBUTE_PTR, CK_DERIVED_KEY, CK_DERIVED_KEY_PTR, CK_INVALID_HANDLE, | ||
CK_OBJECT_HANDLE, CK_OBJECT_HANDLE_PTR, CK_PRF_DATA_PARAM, CK_PRF_DATA_PARAM_PTR, | ||
CK_SP800_108_BYTE_ARRAY, CK_SP800_108_COUNTER, CK_SP800_108_COUNTER_FORMAT, | ||
CK_SP800_108_DKM_LENGTH, CK_SP800_108_DKM_LENGTH_FORMAT, CK_SP800_108_DKM_LENGTH_SUM_OF_KEYS, | ||
CK_SP800_108_DKM_LENGTH_SUM_OF_SEGMENTS, CK_SP800_108_FEEDBACK_KDF_PARAMS, | ||
CK_SP800_108_ITERATION_VARIABLE, CK_SP800_108_KDF_PARAMS, CK_ULONG, | ||
}; | ||
|
||
use crate::object::{Attribute, ObjectHandle}; | ||
|
||
use super::MechanismType; | ||
|
||
/// Endianness of byte representation of data. | ||
#[derive(Debug, Clone, Copy, PartialEq)] | ||
pub enum Endianness { | ||
/// Little endian. | ||
Little, | ||
/// Big endian. | ||
Big, | ||
} | ||
|
||
/// Defines encoding format for a counter value. | ||
/// | ||
/// This structure wraps a `CK_SP800_108_COUNTER_FORMAT` structure. | ||
#[derive(Debug, Clone, Copy)] | ||
#[repr(transparent)] | ||
pub struct KbkdfCounterFormat(CK_SP800_108_COUNTER_FORMAT); | ||
|
||
impl KbkdfCounterFormat { | ||
/// Construct encoding format for KDF's internal counter variable. | ||
/// | ||
/// # Arguments | ||
/// | ||
/// * `endianness` - The endianness of the counter's bit representation. | ||
/// | ||
/// * `width_in_bits` - The number of bits used to represent the counter value. | ||
pub fn new(endianness: Endianness, width_in_bits: NonZeroUsize) -> Self { | ||
Self(CK_SP800_108_COUNTER_FORMAT { | ||
bLittleEndian: (endianness == Endianness::Little).into(), | ||
ulWidthInBits: width_in_bits | ||
.get() | ||
.try_into() | ||
.expect("bit width of KBKDF internal counter does not fit in CK_ULONG"), | ||
}) | ||
} | ||
} | ||
|
||
/// Method for calculating length of DKM (derived key material). | ||
/// | ||
/// Corresponds to CK_SP800_108_DKM_LENGTH_METHOD. | ||
#[derive(Debug, Clone, Copy)] | ||
pub enum KbkdfDkmLengthMethod { | ||
/// Sum of length of all keys derived by given invocation of KDF. | ||
SumOfKeys, | ||
/// Sum of length of all segments of output produced by PRF in given invocation of KDF. | ||
SumOfSegments, | ||
} | ||
|
||
/// Defines encoding format for DKM (derived key material). | ||
/// | ||
/// This structure wraps a `CK_SP800_108_DKM_LENGTH_FORMAT` structure. | ||
#[derive(Debug, Clone, Copy)] | ||
#[repr(transparent)] | ||
pub struct KbkdfDkmLengthFormat(CK_SP800_108_DKM_LENGTH_FORMAT); | ||
|
||
impl KbkdfDkmLengthFormat { | ||
/// Construct encoding format for length value of DKM (derived key material) from KDF. | ||
/// | ||
/// # Arguments | ||
/// | ||
/// * `dkm_length_method` - The method used to calculate the DKM length value. | ||
/// | ||
/// * `endianness` - The endianness of the DKM length value's bit representation. | ||
/// | ||
/// * `width_in_bits` - The number of bits used to represent the DKM length value. | ||
pub fn new( | ||
dkm_length_method: KbkdfDkmLengthMethod, | ||
endianness: Endianness, | ||
width_in_bits: NonZeroUsize, | ||
) -> Self { | ||
Self(CK_SP800_108_DKM_LENGTH_FORMAT { | ||
dkmLengthMethod: match dkm_length_method { | ||
KbkdfDkmLengthMethod::SumOfKeys => CK_SP800_108_DKM_LENGTH_SUM_OF_KEYS, | ||
KbkdfDkmLengthMethod::SumOfSegments => CK_SP800_108_DKM_LENGTH_SUM_OF_SEGMENTS, | ||
}, | ||
bLittleEndian: (endianness == Endianness::Little).into(), | ||
wiktor-k marked this conversation as resolved.
Show resolved
Hide resolved
|
||
ulWidthInBits: width_in_bits | ||
.get() | ||
.try_into() | ||
.expect("bit width of KBKDF DKM length value does not fit in CK_ULONG"), | ||
}) | ||
} | ||
} | ||
|
||
/// The type of a segment of input data for the PRF, for a KBKDF operating in feedback- or double pipeline-mode. | ||
#[derive(Debug, Clone, Copy)] | ||
pub enum PrfDataParamType<'a> { | ||
/// Identifies location of predefined iteration variable in constructed PRF input data. | ||
/// | ||
/// For counter-mode, this must contain a [`KbkdfCounterFormat`]. | ||
/// For feedback- and double-pipeline mode, this must contain [`None`]. | ||
IterationVariable(Option<&'a KbkdfCounterFormat>), | ||
/// Identifies location of counter in constructed PRF input data. | ||
Counter(&'a KbkdfCounterFormat), | ||
/// Identifies location of DKM (derived key material) length value in constructed PRF input data. | ||
DkmLength(&'a KbkdfDkmLengthFormat), | ||
/// Identifies location and value of byte array of data in constructed PRF input data. | ||
ByteArray(&'a [u8]), | ||
} | ||
|
||
/// A segment of input data for the PRF, to be used to construct a sequence of input. | ||
/// | ||
/// This structure wraps a `CK_PRF_DATA_PARAM` structure. | ||
/// | ||
/// * [`PrfDataParamType::IterationVariable`] is required for the KDF in all modes. | ||
/// * In counter-mode, [`PrfDataParamType::IterationVariable`] must contain [`KbkdfCounterFormat`]. | ||
/// In feedback- and double pipeline-mode, it must contain [`None`]. | ||
/// * [`PrfDataParamType::Counter`] must not be present in counter-mode, and can be present at most | ||
/// once in feedback- and double-pipeline modes. | ||
/// * [`PrfDataParamType::DkmLength`] can be present at most once, in any mode. | ||
/// * [`PrfDataParamType::ByteArray`] can be present any amount of times, in any mode. | ||
#[derive(Debug, Clone, Copy)] | ||
#[repr(transparent)] | ||
pub struct PrfDataParam<'a> { | ||
inner: CK_PRF_DATA_PARAM, | ||
/// Marker type to ensure we don't outlive the data | ||
_marker: PhantomData<&'a [u8]>, | ||
} | ||
|
||
impl<'a> PrfDataParam<'a> { | ||
/// Construct data parameter for input of the PRF internal to the KBKDF. | ||
/// | ||
/// # Arguments | ||
/// | ||
/// * `type_` - The specific type and parameters for the data parameter. | ||
pub fn new(type_: PrfDataParamType<'a>) -> Self { | ||
Self { | ||
inner: match type_ { | ||
PrfDataParamType::IterationVariable(None) => CK_PRF_DATA_PARAM { | ||
type_: CK_SP800_108_ITERATION_VARIABLE, | ||
pValue: ptr::null_mut(), | ||
ulValueLen: 0, | ||
}, | ||
PrfDataParamType::IterationVariable(Some(counter_format)) => CK_PRF_DATA_PARAM { | ||
type_: CK_SP800_108_ITERATION_VARIABLE, | ||
pValue: counter_format as *const _ as *mut _, | ||
ulValueLen: size_of::<CK_SP800_108_COUNTER_FORMAT>() as CK_ULONG, | ||
}, | ||
PrfDataParamType::Counter(counter_format) => CK_PRF_DATA_PARAM { | ||
type_: CK_SP800_108_COUNTER, | ||
pValue: counter_format as *const _ as *mut _, | ||
ulValueLen: size_of::<CK_SP800_108_COUNTER_FORMAT>() as CK_ULONG, | ||
}, | ||
PrfDataParamType::DkmLength(dkm_length_format) => CK_PRF_DATA_PARAM { | ||
type_: CK_SP800_108_DKM_LENGTH, | ||
pValue: dkm_length_format as *const _ as *mut _, | ||
ulValueLen: size_of::<CK_SP800_108_DKM_LENGTH_FORMAT>() as CK_ULONG, | ||
}, | ||
PrfDataParamType::ByteArray(data) => CK_PRF_DATA_PARAM { | ||
type_: CK_SP800_108_BYTE_ARRAY, | ||
pValue: data.as_ptr() as *mut _, | ||
ulValueLen: data | ||
.len() | ||
.try_into() | ||
.expect("length of PRF data parameter does not fit in CK_ULONG"), | ||
}, | ||
}, | ||
_marker: PhantomData, | ||
} | ||
} | ||
} | ||
|
||
/// Container for information on an additional key to be derived. | ||
#[derive(Debug)] | ||
pub struct DerivedKey { | ||
template: Pin<Box<[CK_ATTRIBUTE]>>, | ||
hug-dev marked this conversation as resolved.
Show resolved
Hide resolved
|
||
handle: CK_OBJECT_HANDLE, | ||
} | ||
|
||
impl DerivedKey { | ||
/// Construct template for additional key to be derived by KDF. | ||
/// | ||
/// # Arguments | ||
/// | ||
/// * `template` - The template for the key to be derived. | ||
pub fn new(template: &[Attribute]) -> Self { | ||
let template: Box<[CK_ATTRIBUTE]> = template.iter().map(Into::into).collect(); | ||
let template = Pin::new(template); | ||
|
||
Self { | ||
template, | ||
handle: CK_INVALID_HANDLE, | ||
} | ||
} | ||
|
||
/// Return handle for derived key, if it has been created yet | ||
pub fn handle(&self) -> Option<ObjectHandle> { | ||
if self.handle == CK_INVALID_HANDLE { | ||
None | ||
} else { | ||
Some(ObjectHandle::new(self.handle)) | ||
} | ||
} | ||
} | ||
|
||
impl From<&mut DerivedKey> for CK_DERIVED_KEY { | ||
fn from(value: &mut DerivedKey) -> Self { | ||
CK_DERIVED_KEY { | ||
pTemplate: value.template.as_ptr() as CK_ATTRIBUTE_PTR, | ||
ulAttributeCount: value | ||
.template | ||
.len() | ||
.try_into() | ||
.expect("number of attributes in template does not fit in CK_ULONG"), | ||
phKey: &mut value.handle as CK_OBJECT_HANDLE_PTR, | ||
} | ||
} | ||
} | ||
|
||
/// NIST SP 800-108 (aka KBKDF) counter and double pipeline-mode parameters. | ||
/// | ||
/// This structure wraps a `CK_SP800_108_KDF_PARAMS` structure. | ||
#[derive(Debug)] | ||
pub struct KbkdfParams<'a> { | ||
/// Holds own data so that we have a contiguous memory region to give to backend | ||
_additional_derived_keys: Option<Pin<Box<[CK_DERIVED_KEY]>>>, | ||
jacobprudhomme marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
inner: CK_SP800_108_KDF_PARAMS, | ||
/// Marker type to ensure we don't outlive the data | ||
_marker: PhantomData<&'a mut [u8]>, | ||
} | ||
|
||
impl<'a> KbkdfParams<'a> { | ||
/// Construct parameters for NIST SP 800-108 KDF (aka KBKDF) pseudorandom function-based key | ||
/// derivation function, in counter or double pipeline-mode. | ||
/// | ||
/// # Arguments | ||
/// | ||
/// * `prf_mechanism` - The pseudorandom function that underlies the KBKDF operation. | ||
/// | ||
/// * `prf_data_params` - The sequence of data segments used as input data for the PRF. Requires at least [`PrfDataParamType::IterationVariable`]. | ||
/// | ||
/// * `additional_derived_keys` - Any additional keys to be generated by the KDF from the base key. | ||
pub fn new( | ||
prf_mechanism: MechanismType, | ||
prf_data_params: &'a [PrfDataParam<'a>], | ||
additional_derived_keys: Option<&'a mut [DerivedKey]>, | ||
) -> Self { | ||
let mut additional_derived_keys = additional_derived_keys | ||
.map(|keys| { | ||
keys.iter_mut() | ||
.map(Into::into) | ||
.collect::<Box<[CK_DERIVED_KEY]>>() | ||
}) | ||
.map(Pin::new); | ||
|
||
let inner = CK_SP800_108_KDF_PARAMS { | ||
prfType: prf_mechanism.into(), | ||
ulNumberOfDataParams: prf_data_params | ||
.len() | ||
.try_into() | ||
.expect("number of PRF data parameters does not fit in CK_ULONG"), | ||
pDataParams: prf_data_params.as_ptr() as CK_PRF_DATA_PARAM_PTR, | ||
ulAdditionalDerivedKeys: additional_derived_keys.as_ref().map_or(0, |keys| { | ||
keys.len() | ||
.try_into() | ||
.expect("number of additional derived keys does not fit in CK_ULONG") | ||
}), | ||
pAdditionalDerivedKeys: additional_derived_keys | ||
.as_mut() | ||
.map_or(ptr::null_mut(), |keys| { | ||
keys.as_mut_ptr() as CK_DERIVED_KEY_PTR | ||
}), | ||
}; | ||
|
||
Self { | ||
_additional_derived_keys: additional_derived_keys, | ||
|
||
inner, | ||
_marker: PhantomData, | ||
} | ||
} | ||
|
||
pub(crate) fn inner(&self) -> &CK_SP800_108_KDF_PARAMS { | ||
&self.inner | ||
} | ||
} | ||
|
||
/// NIST SP 800-108 (aka KBKDF) feedback-mode parameters. | ||
/// | ||
/// This structure wraps a `CK_SP800_108_FEEDBACK_KDF_PARAMS` structure. | ||
#[derive(Debug)] | ||
pub struct KbkdfFeedbackParams<'a> { | ||
/// Holds own data so that we have a contiguous memory region to give to backend | ||
_additional_derived_keys: Option<Pin<Box<[CK_DERIVED_KEY]>>>, | ||
|
||
inner: CK_SP800_108_FEEDBACK_KDF_PARAMS, | ||
/// Marker type to ensure we don't outlive the data | ||
_marker: PhantomData<&'a mut [u8]>, | ||
} | ||
|
||
impl<'a> KbkdfFeedbackParams<'a> { | ||
/// Construct parameters for NIST SP 800-108 KDF (aka KBKDF) pseuderandom function-based key | ||
/// derivation function, in feedback-mode. | ||
/// | ||
/// # Arguments | ||
/// | ||
/// * `prf_mechanism` - The pseudorandom function that underlies the KBKDF operation. | ||
/// | ||
/// * `prf_data_params` - The sequence of data segments used as input data for the PRF. Requires at least [`PrfDataParamType::IterationVariable`]. | ||
/// | ||
/// * `iv` - The IV to be used for the feedback-mode KDF. | ||
/// | ||
/// * `additional_derived_keys` - Any additional keys to be generated by the KDF from the base key. | ||
pub fn new( | ||
prf_mechanism: MechanismType, | ||
prf_data_params: &'a [PrfDataParam<'a>], | ||
iv: Option<&'a [u8]>, | ||
additional_derived_keys: Option<&'a mut [DerivedKey]>, | ||
) -> Self { | ||
let mut additional_derived_keys = additional_derived_keys | ||
.map(|keys| { | ||
keys.iter_mut() | ||
.map(Into::into) | ||
.collect::<Box<[CK_DERIVED_KEY]>>() | ||
}) | ||
.map(Pin::new); | ||
|
||
let inner = CK_SP800_108_FEEDBACK_KDF_PARAMS { | ||
prfType: prf_mechanism.into(), | ||
ulNumberOfDataParams: prf_data_params | ||
.len() | ||
.try_into() | ||
.expect("number of PRF data parameters does not fit in CK_ULONG"), | ||
pDataParams: prf_data_params.as_ptr() as CK_PRF_DATA_PARAM_PTR, | ||
ulIVLen: iv.map_or(0, |iv| { | ||
iv.len() | ||
.try_into() | ||
.expect("IV length does not fit in CK_ULONG") | ||
}), | ||
pIV: iv.map_or(ptr::null_mut(), |iv| iv.as_ptr() as *mut _), | ||
ulAdditionalDerivedKeys: additional_derived_keys.as_ref().map_or(0, |keys| { | ||
keys.len() | ||
.try_into() | ||
.expect("number of additional derived keys does not fit in CK_ULONG") | ||
}), | ||
pAdditionalDerivedKeys: additional_derived_keys | ||
.as_mut() | ||
.map_or(ptr::null_mut(), |keys| { | ||
keys.as_mut_ptr() as CK_DERIVED_KEY_PTR | ||
}), | ||
}; | ||
|
||
Self { | ||
_additional_derived_keys: additional_derived_keys, | ||
|
||
inner, | ||
_marker: PhantomData, | ||
} | ||
} | ||
|
||
pub(crate) fn inner(&self) -> &CK_SP800_108_FEEDBACK_KDF_PARAMS { | ||
&self.inner | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.