portable_rustls/crypto/hmac.rs
1use alloc::boxed::Box;
2
3use zeroize::Zeroize;
4
5/// A concrete HMAC implementation, for a single cryptographic hash function.
6///
7/// You should have one object that implements this trait for HMAC-SHA256, another
8/// for HMAC-SHA384, etc.
9pub trait Hmac: Send + Sync {
10 /// Prepare to use `key` as a HMAC key.
11 fn with_key(&self, key: &[u8]) -> Box<dyn Key>;
12
13 /// Give the length of the underlying hash function. In RFC2104 terminology this is `L`.
14 fn hash_output_len(&self) -> usize;
15
16 /// Return `true` if this is backed by a FIPS-approved implementation.
17 #[cfg(unstable_api_not_supported)] // [FIPS REMOVED FROM THIS FORK]
18 fn fips(&self) -> bool {
19 false
20 }
21}
22
23/// A HMAC tag, stored as a value.
24#[derive(Clone)]
25pub struct Tag {
26 buf: [u8; Self::MAX_LEN],
27 used: usize,
28}
29
30impl Tag {
31 /// Build a tag by copying a byte slice.
32 ///
33 /// The slice can be up to [`Tag::MAX_LEN`] bytes in length.
34 pub fn new(bytes: &[u8]) -> Self {
35 let mut tag = Self {
36 buf: [0u8; Self::MAX_LEN],
37 used: bytes.len(),
38 };
39 tag.buf[..bytes.len()].copy_from_slice(bytes);
40 tag
41 }
42
43 /// Maximum supported HMAC tag size: supports up to SHA512.
44 pub const MAX_LEN: usize = 64;
45}
46
47impl Drop for Tag {
48 fn drop(&mut self) {
49 self.buf.zeroize();
50 }
51}
52
53impl AsRef<[u8]> for Tag {
54 fn as_ref(&self) -> &[u8] {
55 &self.buf[..self.used]
56 }
57}
58
59/// A HMAC key that is ready for use.
60///
61/// The algorithm used is implicit in the `Hmac` object that produced the key.
62pub trait Key: Send + Sync {
63 /// Calculates a tag over `data` -- a slice of byte slices.
64 fn sign(&self, data: &[&[u8]]) -> Tag {
65 self.sign_concat(&[], data, &[])
66 }
67
68 /// Calculates a tag over the concatenation of `first`, the items in `middle`, and `last`.
69 fn sign_concat(&self, first: &[u8], middle: &[&[u8]], last: &[u8]) -> Tag;
70
71 /// Returns the length of the tag returned by a computation using
72 /// this key.
73 fn tag_len(&self) -> usize;
74}