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
use clear_on_drop::clear::Clear;
use failure::bail;
use hmac::crypto_mac::generic_array::{
typenum::{Unsigned, U32, U48, U64},
GenericArray,
};
use hmac::{crypto_mac::MacResult, Hmac, Mac as _};
use rand_core::{CryptoRng, RngCore};
use sha2::{digest::BlockInput, Sha256, Sha384, Sha512};
use smallvec::{smallvec, SmallVec};
use std::{borrow::Cow, fmt};
use crate::{Algorithm, AlgorithmSignature};
macro_rules! define_hmac_key {
(
$(#[$($attr:meta)+])*
struct $name:ident<$digest:ident, $out_size:ident>([u8; $buffer_size:expr]);
) => {
$(#[$($attr)+])*
#[derive(Clone)]
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 Drop for $name {
fn drop(&mut self) {
Clear::clear(&mut self.0);
}
}
impl $name {
pub fn generate<R: CryptoRng + RngCore>(rng: &mut R) -> Self {
let mut key = $name(smallvec![0; <$digest as BlockInput>::BlockSize::to_usize()]);
rng.fill_bytes(&mut key.0);
key
}
pub fn hmac(&self, message: impl AsRef<[u8]>) -> MacResult<$out_size> {
let mut hmac = Hmac::<$digest>::new_varkey(&self.0)
.expect("HMACs work with any key size");
hmac.input(message.as_ref());
hmac.result()
}
}
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
}
}
};
}
define_hmac_key! {
struct Hs256Key<Sha256, U32>([u8; 64]);
}
define_hmac_key! {
struct Hs384Key<Sha384, U48>([u8; 128]);
}
define_hmac_key! {
struct Hs512Key<Sha512, U64>([u8; 128]);
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Hs256;
impl AlgorithmSignature for MacResult<U32> {
fn try_from_slice(bytes: &[u8]) -> Result<Self, failure::Error> {
if bytes.len() != 32 {
bail!("Invalid signature length");
}
Ok(MacResult::new(GenericArray::clone_from_slice(bytes)))
}
fn as_bytes(&self) -> Cow<[u8]> {
Cow::Owned(self.clone().code().to_vec())
}
}
impl Algorithm for Hs256 {
type SigningKey = Hs256Key;
type VerifyingKey = Hs256Key;
type Signature = MacResult<U32>;
fn name(&self) -> Cow<'static, str> {
Cow::Borrowed("HS256")
}
fn sign(&self, signing_key: &Self::SigningKey, message: &[u8]) -> Self::Signature {
signing_key.hmac(message)
}
fn verify_signature(
&self,
signature: &Self::Signature,
verifying_key: &Self::VerifyingKey,
message: &[u8],
) -> bool {
verifying_key.hmac(message) == *signature
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Hs384;
impl AlgorithmSignature for MacResult<U48> {
fn try_from_slice(bytes: &[u8]) -> Result<Self, failure::Error> {
if bytes.len() != 48 {
bail!("Invalid signature length");
}
Ok(MacResult::new(GenericArray::clone_from_slice(bytes)))
}
fn as_bytes(&self) -> Cow<[u8]> {
Cow::Owned(self.clone().code().to_vec())
}
}
impl Algorithm for Hs384 {
type SigningKey = Hs384Key;
type VerifyingKey = Hs384Key;
type Signature = MacResult<U48>;
fn name(&self) -> Cow<'static, str> {
Cow::Borrowed("HS384")
}
fn sign(&self, signing_key: &Self::SigningKey, message: &[u8]) -> Self::Signature {
signing_key.hmac(message)
}
fn verify_signature(
&self,
signature: &Self::Signature,
verifying_key: &Self::VerifyingKey,
message: &[u8],
) -> bool {
verifying_key.hmac(message) == *signature
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Hs512;
impl AlgorithmSignature for MacResult<U64> {
fn try_from_slice(bytes: &[u8]) -> Result<Self, failure::Error> {
if bytes.len() != 64 {
bail!("Invalid signature length");
}
Ok(MacResult::new(GenericArray::clone_from_slice(bytes)))
}
fn as_bytes(&self) -> Cow<[u8]> {
Cow::Owned(self.clone().code().to_vec())
}
}
impl Algorithm for Hs512 {
type SigningKey = Hs512Key;
type VerifyingKey = Hs512Key;
type Signature = MacResult<U64>;
fn name(&self) -> Cow<'static, str> {
Cow::Borrowed("HS512")
}
fn sign(&self, signing_key: &Self::SigningKey, message: &[u8]) -> Self::Signature {
signing_key.hmac(message)
}
fn verify_signature(
&self,
signature: &Self::Signature,
verifying_key: &Self::VerifyingKey,
message: &[u8],
) -> bool {
verifying_key.hmac(message) == *signature
}
}