use crate::error::Unspecified;
use crate::{constant_time, digest, hkdf};
use aws_lc::{
HMAC_CTX_cleanup, HMAC_CTX_copy_ex, HMAC_CTX_init, HMAC_Final, HMAC_Init_ex, HMAC_Update,
HMAC_CTX,
};
use std::mem::MaybeUninit;
use std::os::raw::c_uint;
use std::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
}
}
pub static HMAC_SHA1_FOR_LEGACY_USE_ONLY: Algorithm = Algorithm(&digest::SHA1_FOR_LEGACY_USE_ONLY);
pub static HMAC_SHA256: Algorithm = Algorithm(&digest::SHA256);
pub static HMAC_SHA384: Algorithm = Algorithm(&digest::SHA384);
pub static 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(HMAC_CTX);
impl LcHmacCtx {
fn as_mut_ptr(&mut self) -> *mut HMAC_CTX {
&mut self.0
}
fn as_ptr(&self) -> *const HMAC_CTX {
&self.0
}
fn try_clone(&self) -> Result<Self, Unspecified> {
unsafe {
let mut hmac_ctx = MaybeUninit::<HMAC_CTX>::uninit();
HMAC_CTX_init(hmac_ctx.as_mut_ptr());
let mut hmac_ctx = hmac_ctx.assume_init();
if 1 != HMAC_CTX_copy_ex(&mut hmac_ctx, self.as_ptr()) {
return Err(Unspecified);
}
Ok(LcHmacCtx(hmac_ctx))
}
}
}
unsafe impl Send for LcHmacCtx {}
impl Drop for LcHmacCtx {
fn drop(&mut self) {
unsafe { HMAC_CTX_cleanup(self.as_mut_ptr()) }
}
}
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 {}
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.0.output_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> {
unsafe {
let mut ctx = MaybeUninit::<HMAC_CTX>::uninit();
HMAC_CTX_init(ctx.as_mut_ptr());
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(),
*evp_md_type,
null_mut(),
) {
return Err(Unspecified);
};
let result = Self {
algorithm,
ctx: LcHmacCtx(ctx.assume_init()),
};
Ok(result)
}
}
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.digest_algorithm().output_len
}
}
impl From<hkdf::Okm<'_, Algorithm>> for Key {
fn from(okm: hkdf::Okm<Algorithm>) -> Self {
Self::construct(*okm.len(), |buf| okm.fill(buf)).unwrap()
}
}
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().cast(),
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 mut out_len = MaybeUninit::<c_uint>::uninit();
unsafe {
if 1 != HMAC_Final(
self.key.get_hmac_ctx_ptr(),
output.as_mut_ptr(),
out_len.as_mut_ptr(),
) {
return Err(Unspecified);
}
Ok(Tag {
msg: output,
msg_len: out_len.assume_init() as usize,
})
}
}
}
#[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 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};
#[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_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_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());
}
}
}