1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
//! JWT algorithms based on HMACs.

use core::{fmt, num::NonZeroUsize};

use hmac::{
    digest::{
        generic_array::{typenum::Unsigned, GenericArray},
        CtOutput,
    },
    Hmac, Mac as _,
};
use rand_core::{CryptoRng, RngCore};
use sha2::{
    digest::{core_api::BlockSizeUser, OutputSizeUser},
    Sha256, Sha384, Sha512,
};
use smallvec::{smallvec, SmallVec};
use zeroize::Zeroize;

use crate::{
    alg::{SecretBytes, SigningKey, StrongKey, VerifyingKey, WeakKeyError},
    alloc::Cow,
    jwk::{JsonWebKey, JwkError, KeyType},
    Algorithm, AlgorithmSignature,
};

macro_rules! define_hmac_signature {
    (
        $(#[$($attr:meta)+])*
        struct $name:ident<$digest:ident>;
    ) => {
        $(#[$($attr)+])*
        #[derive(Clone, PartialEq, Eq)]
        pub struct $name(CtOutput<Hmac<$digest>>);

        impl fmt::Debug for $name {
            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.debug_tuple(stringify!($name)).field(&"_").finish()
            }
        }

        impl AlgorithmSignature for $name {
            const LENGTH: Option<NonZeroUsize> =
                NonZeroUsize::new(<$digest as OutputSizeUser>::OutputSize::USIZE);

            fn try_from_slice(bytes: &[u8]) -> anyhow::Result<Self> {
                let bytes = GenericArray::clone_from_slice(bytes);
                Ok(Self(CtOutput::new(bytes)))
            }

            fn as_bytes(&self) -> Cow<'_, [u8]> {
                Cow::Owned(self.0.clone().into_bytes().to_vec())
            }
        }
    };
}

define_hmac_signature!(
    /// Signature produced by the [`Hs256`] algorithm.
    struct Hs256Signature<Sha256>;
);
define_hmac_signature!(
    /// Signature produced by the [`Hs384`] algorithm.
    struct Hs384Signature<Sha384>;
);
define_hmac_signature!(
    /// Signature produced by the [`Hs512`] algorithm.
    struct Hs512Signature<Sha512>;
);

macro_rules! define_hmac_key {
    (
        $(#[$($attr:meta)+])*
        struct $name:ident<$digest:ident>([u8; $buffer_size:expr]);
    ) => {
        $(#[$($attr)+])*
        #[derive(Clone, Zeroize)]
        #[zeroize(drop)]
        pub struct $name(pub(crate) SmallVec<[u8; $buffer_size]>);

        impl fmt::Debug for $name {
            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.debug_tuple(stringify!($name)).field(&"_").finish()
            }
        }

        impl $name {
            /// Generates a random key using a cryptographically secure RNG.
            pub fn generate<R: CryptoRng + RngCore>(rng: &mut R) -> StrongKey<Self> {
                let mut key = $name(smallvec![0; <$digest as BlockSizeUser>::BlockSize::to_usize()]);
                rng.fill_bytes(&mut key.0);
                StrongKey(key)
            }

            /// Creates a key from the specified `bytes`.
            pub fn new(bytes: impl AsRef<[u8]>) -> Self {
                Self(bytes.as_ref().into())
            }

            /// Computes HMAC with this key and the specified `message`.
            fn hmac(&self, message: impl AsRef<[u8]>) -> CtOutput<Hmac<$digest>> {
                let mut hmac = Hmac::<$digest>::new_from_slice(&self.0)
                    .expect("HMACs work with any key size");
                hmac.update(message.as_ref());
                hmac.finalize()
            }
        }

        impl From<&[u8]> for $name {
            fn from(bytes: &[u8]) -> Self {
                $name(bytes.into())
            }
        }

        impl AsRef<[u8]> for $name {
            fn as_ref(&self) -> &[u8] {
                &self.0
            }
        }

        impl AsMut<[u8]> for $name {
            fn as_mut(&mut self) -> &mut [u8] {
                &mut self.0
            }
        }

        impl TryFrom<$name> for StrongKey<$name> {
            type Error = WeakKeyError<$name>;

            fn try_from(value: $name) -> Result<Self, Self::Error> {
                if value.0.len() >= <$digest as BlockSizeUser>::BlockSize::to_usize() {
                    Ok(StrongKey(value))
                } else {
                    Err(WeakKeyError(value))
                }
            }
        }
    };
}

define_hmac_key! {
    /// Signing / verifying key for `HS256` algorithm. Zeroed on drop.
    struct Hs256Key<Sha256>([u8; 64]);
}
define_hmac_key! {
    /// Signing / verifying key for `HS384` algorithm. Zeroed on drop.
    struct Hs384Key<Sha384>([u8; 128]);
}
define_hmac_key! {
    /// Signing / verifying key for `HS512` algorithm. Zeroed on drop.
    struct Hs512Key<Sha512>([u8; 128]);
}

/// `HS256` signing algorithm.
///
/// See [RFC 7518] for the algorithm specification.
///
/// [RFC 7518]: https://tools.ietf.org/html/rfc7518#section-3.2
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct Hs256;

impl Algorithm for Hs256 {
    type SigningKey = Hs256Key;
    type VerifyingKey = Hs256Key;
    type Signature = Hs256Signature;

    fn name(&self) -> Cow<'static, str> {
        Cow::Borrowed("HS256")
    }

    fn sign(&self, signing_key: &Self::SigningKey, message: &[u8]) -> Self::Signature {
        Hs256Signature(signing_key.hmac(message))
    }

    fn verify_signature(
        &self,
        signature: &Self::Signature,
        verifying_key: &Self::VerifyingKey,
        message: &[u8],
    ) -> bool {
        verifying_key.hmac(message) == signature.0
    }
}

/// `HS384` signing algorithm.
///
/// See [RFC 7518] for the algorithm specification.
///
/// [RFC 7518]: https://tools.ietf.org/html/rfc7518#section-3.2
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct Hs384;

impl Algorithm for Hs384 {
    type SigningKey = Hs384Key;
    type VerifyingKey = Hs384Key;
    type Signature = Hs384Signature;

    fn name(&self) -> Cow<'static, str> {
        Cow::Borrowed("HS384")
    }

    fn sign(&self, signing_key: &Self::SigningKey, message: &[u8]) -> Self::Signature {
        Hs384Signature(signing_key.hmac(message))
    }

    fn verify_signature(
        &self,
        signature: &Self::Signature,
        verifying_key: &Self::VerifyingKey,
        message: &[u8],
    ) -> bool {
        verifying_key.hmac(message) == signature.0
    }
}

/// `HS512` signing algorithm.
///
/// See [RFC 7518] for the algorithm specification.
///
/// [RFC 7518]: https://tools.ietf.org/html/rfc7518#section-3.2
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct Hs512;

impl Algorithm for Hs512 {
    type SigningKey = Hs512Key;
    type VerifyingKey = Hs512Key;
    type Signature = Hs512Signature;

    fn name(&self) -> Cow<'static, str> {
        Cow::Borrowed("HS512")
    }

    fn sign(&self, signing_key: &Self::SigningKey, message: &[u8]) -> Self::Signature {
        Hs512Signature(signing_key.hmac(message))
    }

    fn verify_signature(
        &self,
        signature: &Self::Signature,
        verifying_key: &Self::VerifyingKey,
        message: &[u8],
    ) -> bool {
        verifying_key.hmac(message) == signature.0
    }
}

macro_rules! impl_key_traits {
    ($key:ident<$alg:ident>) => {
        impl SigningKey<$alg> for $key {
            fn from_slice(raw: &[u8]) -> anyhow::Result<Self> {
                Ok(Self::from(raw))
            }

            fn to_verifying_key(&self) -> Self {
                self.clone()
            }

            fn as_bytes(&self) -> SecretBytes<'_> {
                SecretBytes::borrowed(self.as_ref())
            }
        }

        impl VerifyingKey<$alg> for $key {
            fn from_slice(raw: &[u8]) -> anyhow::Result<Self> {
                Ok(Self::from(raw))
            }

            fn as_bytes(&self) -> Cow<'_, [u8]> {
                Cow::Borrowed(self.as_ref())
            }
        }

        impl<'a> From<&'a $key> for JsonWebKey<'a> {
            fn from(key: &'a $key) -> JsonWebKey<'a> {
                JsonWebKey::Symmetric {
                    secret: SecretBytes::borrowed(key.as_ref()),
                }
            }
        }

        impl TryFrom<&JsonWebKey<'_>> for $key {
            type Error = JwkError;

            fn try_from(jwk: &JsonWebKey<'_>) -> Result<Self, Self::Error> {
                match jwk {
                    JsonWebKey::Symmetric { secret } => Ok(Self::new(secret)),
                    _ => Err(JwkError::key_type(jwk, KeyType::Symmetric)),
                }
            }
        }
    };
}

impl_key_traits!(Hs256Key<Hs256>);
impl_key_traits!(Hs384Key<Hs384>);
impl_key_traits!(Hs512Key<Hs512>);