use crate::error::Unspecified;
use crate::fips::indicator_check;
use crate::ptr::LcPtr;
use crate::wolfcrypt_rs::{
HMAC_CTX_copy, HMAC_CTX_new, HMAC_Final, HMAC_Init_ex, HMAC_Update, HMAC_CTX,
};
use crate::{constant_time, digest, hkdf};
use core::ffi::c_uint;
use core::mem::MaybeUninit;
use core::ptr::null_mut;
#[deprecated]
pub type Signature = Tag;
#[deprecated]
pub type SigningContext = Context;
#[deprecated]
pub type SigningKey = Key;
#[deprecated]
pub type VerificationKey = Key;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Algorithm(&'static digest::Algorithm);
impl Algorithm {
#[inline]
#[must_use]
pub fn digest_algorithm(&self) -> &'static digest::Algorithm {
self.0
}
#[inline]
#[must_use]
pub fn tag_len(&self) -> usize {
self.digest_algorithm().output_len
}
}
pub const HMAC_SHA1_FOR_LEGACY_USE_ONLY: Algorithm = Algorithm(&digest::SHA1_FOR_LEGACY_USE_ONLY);
pub const HMAC_SHA224: Algorithm = Algorithm(&digest::SHA224);
pub const HMAC_SHA256: Algorithm = Algorithm(&digest::SHA256);
pub const HMAC_SHA384: Algorithm = Algorithm(&digest::SHA384);
pub const HMAC_SHA512: Algorithm = Algorithm(&digest::SHA512);
#[derive(Clone, Copy, Debug)]
pub struct Tag {
msg: [u8; digest::MAX_OUTPUT_LEN],
msg_len: usize,
}
impl AsRef<[u8]> for Tag {
#[inline]
fn as_ref(&self) -> &[u8] {
&self.msg[..self.msg_len]
}
}
struct LcHmacCtx(LcPtr<HMAC_CTX>);
impl LcHmacCtx {
fn new() -> Result<Self, Unspecified> {
let ctx = LcPtr::new(unsafe { HMAC_CTX_new() }).map_err(|_| Unspecified)?;
Ok(LcHmacCtx(ctx))
}
fn as_mut_ptr(&mut self) -> *mut HMAC_CTX {
self.0.as_mut_ptr()
}
fn as_ptr(&self) -> *const HMAC_CTX {
self.0.as_const_ptr()
}
fn try_clone(&self) -> Result<Self, Unspecified> {
let mut new_ctx = Self::new()?;
unsafe {
if 1 != HMAC_CTX_copy(new_ctx.as_mut_ptr(), self.as_ptr() as *mut HMAC_CTX) {
return Err(Unspecified);
}
}
Ok(new_ctx)
}
}
unsafe impl Send for LcHmacCtx {}
impl Clone for LcHmacCtx {
fn clone(&self) -> Self {
self.try_clone().expect("Unable to clone LcHmacCtx")
}
}
#[derive(Clone)]
pub struct Key {
pub(crate) algorithm: Algorithm,
ctx: LcHmacCtx,
}
unsafe impl Send for Key {}
unsafe impl Sync for Key {}
#[allow(clippy::missing_fields_in_debug)]
impl core::fmt::Debug for Key {
fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
f.debug_struct("Key")
.field("algorithm", &self.algorithm.digest_algorithm())
.finish()
}
}
impl Key {
pub fn generate(
algorithm: Algorithm,
rng: &dyn crate::rand::SecureRandom,
) -> Result<Self, Unspecified> {
Self::construct(algorithm, |buf| rng.fill(buf))
}
fn construct<F>(algorithm: Algorithm, fill: F) -> Result<Self, Unspecified>
where
F: FnOnce(&mut [u8]) -> Result<(), Unspecified>,
{
let mut key_bytes = [0; digest::MAX_OUTPUT_LEN];
let key_bytes = &mut key_bytes[..algorithm.tag_len()];
fill(key_bytes)?;
Ok(Self::new(algorithm, key_bytes))
}
#[inline]
#[must_use]
pub fn new(algorithm: Algorithm, key_value: &[u8]) -> Self {
Key::try_new(algorithm, key_value).expect("Unable to create HmacContext")
}
fn try_new(algorithm: Algorithm, key_value: &[u8]) -> Result<Self, Unspecified> {
let mut ctx = LcHmacCtx::new()?;
unsafe {
let evp_md_type = digest::match_digest_type(&algorithm.digest_algorithm().id);
if 1 != HMAC_Init_ex(
ctx.as_mut_ptr(),
key_value.as_ptr().cast(),
key_value.len() as core::ffi::c_int,
evp_md_type.as_const_ptr(),
null_mut(),
) {
return Err(Unspecified);
}
}
Ok(Self { algorithm, ctx })
}
unsafe fn get_hmac_ctx_ptr(&mut self) -> *mut HMAC_CTX {
self.ctx.as_mut_ptr()
}
#[inline]
#[must_use]
pub fn algorithm(&self) -> Algorithm {
Algorithm(self.algorithm.digest_algorithm())
}
}
impl hkdf::KeyType for Algorithm {
#[inline]
fn len(&self) -> usize {
self.tag_len()
}
}
#[cfg(feature = "std")]
impl From<hkdf::Okm<'_, Algorithm>> for Key {
fn from(okm: hkdf::Okm<Algorithm>) -> Self {
Self::construct(*okm.len(), |buf| okm.fill(buf)).unwrap()
}
}
#[cfg(not(feature = "std"))]
impl TryFrom<hkdf::Okm<'_, Algorithm>> for Key {
type Error = Unspecified;
fn try_from(okm: hkdf::Okm<Algorithm>) -> Result<Self, Unspecified> {
Self::construct(*okm.len(), |buf| okm.fill(buf))
}
}
pub struct Context {
key: Key,
}
impl Clone for Context {
fn clone(&self) -> Self {
Self {
key: self.key.clone(),
}
}
}
unsafe impl Send for Context {}
impl core::fmt::Debug for Context {
fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
f.debug_struct("Context")
.field("algorithm", &self.key.algorithm.digest_algorithm())
.finish()
}
}
impl Context {
#[inline]
#[must_use]
pub fn with_key(signing_key: &Key) -> Self {
Self {
key: signing_key.clone(),
}
}
#[inline]
pub fn update(&mut self, data: &[u8]) {
Self::try_update(self, data).expect("HMAC_Update failed");
}
#[inline]
fn try_update(&mut self, data: &[u8]) -> Result<(), Unspecified> {
unsafe {
if 1 != HMAC_Update(self.key.get_hmac_ctx_ptr(), data.as_ptr(), data.len()) {
return Err(Unspecified);
}
}
Ok(())
}
#[inline]
#[must_use]
pub fn sign(self) -> Tag {
Self::try_sign(self).expect("HMAC_Final failed")
}
#[inline]
fn try_sign(mut self) -> Result<Tag, Unspecified> {
let mut output = [0u8; digest::MAX_OUTPUT_LEN];
let msg_len = {
let result = internal_sign(&mut self, &mut output)?;
result.len()
};
Ok(Tag {
msg: output,
msg_len,
})
}
}
#[inline]
pub(crate) fn internal_sign<'in_out>(
ctx: &mut Context,
output: &'in_out mut [u8],
) -> Result<&'in_out mut [u8], Unspecified> {
let tag_len = ctx.key.algorithm().tag_len();
if output.len() < tag_len {
return Err(Unspecified);
}
let mut out_len = MaybeUninit::<c_uint>::uninit();
if 1 != indicator_check!(unsafe {
HMAC_Final(
ctx.key.get_hmac_ctx_ptr(),
output.as_mut_ptr(),
out_len.as_mut_ptr(),
)
}) {
return Err(Unspecified);
}
let actual_len = unsafe { out_len.assume_init() } as usize;
debug_assert!(
actual_len == tag_len,
"HMAC tag length {actual_len} does not match expected length {tag_len}"
);
Ok(&mut output[0..tag_len])
}
#[inline]
#[must_use]
pub fn sign(key: &Key, data: &[u8]) -> Tag {
let mut ctx = Context::with_key(key);
ctx.update(data);
ctx.sign()
}
#[inline]
pub fn sign_to_buffer<'out>(
key: &Key,
data: &[u8],
output: &'out mut [u8],
) -> Result<&'out mut [u8], Unspecified> {
let mut ctx = Context::with_key(key);
ctx.update(data);
internal_sign(&mut ctx, output)
}
#[inline]
pub fn verify(key: &Key, data: &[u8], tag: &[u8]) -> Result<(), Unspecified> {
constant_time::verify_slices_are_equal(sign(key, data).as_ref(), tag)
}
#[cfg(test)]
mod tests {
use crate::{hmac, rand};
#[cfg(feature = "fips")]
mod fips;
#[test]
fn hmac_algorithm_properties() {
assert_eq!(hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY.tag_len(), 20);
assert_eq!(hmac::HMAC_SHA224.tag_len(), 28);
assert_eq!(hmac::HMAC_SHA256.tag_len(), 32);
assert_eq!(hmac::HMAC_SHA384.tag_len(), 48);
assert_eq!(hmac::HMAC_SHA512.tag_len(), 64);
}
#[test]
fn hmac_internal_sign_too_small_buffer() {
let rng = rand::SystemRandom::new();
for algorithm in &[
hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY,
hmac::HMAC_SHA224,
hmac::HMAC_SHA256,
hmac::HMAC_SHA384,
hmac::HMAC_SHA512,
] {
let key = hmac::Key::generate(*algorithm, &rng).unwrap();
let data = b"hello, world";
let mut small_buf = vec![0u8; algorithm.tag_len() - 1];
let mut ctx = hmac::Context::with_key(&key);
ctx.update(data);
assert!(super::internal_sign(&mut ctx, &mut small_buf).is_err());
let mut empty_buf = vec![];
let mut ctx = hmac::Context::with_key(&key);
ctx.update(data);
assert!(super::internal_sign(&mut ctx, &mut empty_buf).is_err());
}
}
#[test]
pub fn hmac_signing_key_coverage() {
const HELLO_WORLD_GOOD: &[u8] = b"hello, world";
const HELLO_WORLD_BAD: &[u8] = b"hello, worle";
let rng = rand::SystemRandom::new();
for algorithm in &[
hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY,
hmac::HMAC_SHA224,
hmac::HMAC_SHA256,
hmac::HMAC_SHA384,
hmac::HMAC_SHA512,
] {
let key = hmac::Key::generate(*algorithm, &rng).unwrap();
let tag = hmac::sign(&key, HELLO_WORLD_GOOD);
println!("{key:?}");
assert!(hmac::verify(&key, HELLO_WORLD_GOOD, tag.as_ref()).is_ok());
assert!(hmac::verify(&key, HELLO_WORLD_BAD, tag.as_ref()).is_err());
}
}
#[test]
fn hmac_coverage() {
assert_ne!(hmac::HMAC_SHA256, hmac::HMAC_SHA384);
for &alg in &[
hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY,
hmac::HMAC_SHA224,
hmac::HMAC_SHA256,
hmac::HMAC_SHA384,
hmac::HMAC_SHA512,
] {
let key = hmac::Key::new(alg, &[0; 32]);
let mut ctx = hmac::Context::with_key(&key);
ctx.update(b"hello, world");
let ctx_clone = ctx.clone();
let orig_tag = ctx.sign();
let clone_tag = ctx_clone.sign();
assert_eq!(orig_tag.as_ref(), clone_tag.as_ref());
assert_eq!(orig_tag.clone().as_ref(), clone_tag.as_ref());
}
}
#[test]
fn hmac_sign_to_buffer_test() {
let rng = rand::SystemRandom::new();
for &algorithm in &[
hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY,
hmac::HMAC_SHA224,
hmac::HMAC_SHA256,
hmac::HMAC_SHA384,
hmac::HMAC_SHA512,
] {
let key = hmac::Key::generate(algorithm, &rng).unwrap();
let data = b"hello, world";
let tag_len = algorithm.tag_len();
let mut output = vec![0u8; tag_len];
let result = hmac::sign_to_buffer(&key, data, &mut output).unwrap();
assert_eq!(result.len(), tag_len);
let tag = hmac::sign(&key, data);
assert_eq!(result, tag.as_ref());
assert!(hmac::verify(&key, data, result).is_ok());
assert_eq!(output.as_slice(), tag.as_ref());
assert!(hmac::verify(&key, data, output.as_slice()).is_ok());
let mut large_output = vec![0u8; tag_len + 10];
let result2 = hmac::sign_to_buffer(&key, data, &mut large_output).unwrap();
assert_eq!(result2.len(), tag_len);
assert_eq!(result2, tag.as_ref());
assert!(hmac::verify(&key, data, result2).is_ok());
assert_eq!(&large_output[0..tag_len], tag.as_ref());
}
}
#[test]
fn hmac_sign_to_buffer_too_small_test() {
let key = hmac::Key::new(hmac::HMAC_SHA256, &[0; 32]);
let data = b"hello";
let mut small_buffer = vec![0u8; hmac::HMAC_SHA256.tag_len() - 1];
assert!(hmac::sign_to_buffer(&key, data, &mut small_buffer).is_err());
let mut empty_buffer = vec![];
assert!(hmac::sign_to_buffer(&key, data, &mut empty_buffer).is_err());
}
}