hmac-serialiser 0.3.1

HMAC Serialisers to cryptographically sign data like Python's ItsDangerous library but in rust.
Documentation
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
//! # HMAC Signer
//!
//! `hmac-serialiser` is a Rust library for generating and verifying HMAC signatures for secure data transmission.
//!
//! Regarding the cryptographic implementations, you can choose which implementations to use from via the `features` flag in the `Cargo.toml` file:
//! - `rust_crypto` (default)
//!   - the underlying [SHA1](https://crates.io/crates/sha1), [SHA2](https://crates.io/crates/sha2), [HMAC](https://crates.io/crates/hmac), and [HKDF](https://crates.io/crates/hkdf) implementations are by [RustCrypto](https://github.com/RustCrypto).
//! - `ring`
//!   - The underlying SHA1, SHA2, HMAC, and HKDF implementations are from the [ring](https://crates.io/crates/ring) crate.
//!
//! Additionally, the data serialisation and de-serialisation uses the [serde](https://crates.io/crates/serde) crate and
//! the signed data is then encoded or decoded using the [base64](https://crates.io/crates/base64) crate.
//!
//! ## License
//!
//! This library is licensed under the MIT license.
//!
//! ## Features
//!
//! - Supports various encoding schemes for signatures.
//! - Flexible HMAC signer logic for custom data types.
//! - Provides a convenient interface for signing and verifying data.
//!
//! ## Example
//!
//! ```rust
//! use hmac_serialiser::{Encoder, HmacSigner, KeyInfo, Payload, Algorithm};
//! use serde::{Serialize, Deserialize};
//!
//! #[derive(Serialize, Deserialize, Debug)]
//! struct UserData {
//!     // Add your data fields here
//!     username: String,
//!     email: String,
//! }
//!
//! impl Payload for UserData {
//!     fn get_exp(&self) -> Option<chrono::DateTime<chrono::Utc>> {
//!         // Add logic to retrieve expiration time if needed
//!         None
//!     }
//! }
//!
//! fn main() {
//!     // Define your secret key, salt, and optional info
//!     let key_info = KeyInfo {
//!         key: b"your_secret_key".to_vec(),
//!         salt: b"your_salt".to_vec(),
//!         info: vec![], // empty info
//!     };
//!
//!     // Initialize the HMAC signer
//!     let signer = HmacSigner::new(key_info, Algorithm::SHA256, Encoder::UrlSafeNoPadding);
//!
//!     // Serialize your data
//!     let user_data = UserData {
//!         username: "user123".to_string(),
//!         email: "user123@example.com".to_string(),
//!     };
//!
//!     // Sign the data (safe to use by clients)
//!     let token = signer.sign(&user_data);
//!     println!("Token: {}", token);
//!     
//!     // Verify the token given by the client
//!     let verified_data: UserData = signer.unsign(&token)
//!         .expect("Failed to verify token");
//!     println!("Verified data: {:?}", verified_data);
//! }
//! ```
//!
//! ## Supported Encoders
//!
//! - `Standard`: Standard base64 encoding.
//! - `UrlSafe`: URL-safe base64 encoding.
//! - `StandardNoPadding`: Standard base64 encoding without padding.
//! - `UrlSafeNoPadding`: URL-safe base64 encoding without padding. (Default)
//!
//! ## Supported HMAC Algorithms
//!
//! - `SHA1`
//! - `SHA256` (Default)
//! - `SHA384`
//! - `SHA512`
//!
//! Note: Although SHA1 is cryptographically broken, HMAC-SHA1 is not used for integrity checks like file hash checks.
//! Therefore, it is still considered secure to use HMAC-SHA1 to verify the authenticity of a given payload.
//! However, it is still recommended to choose a stronger hash function like SHA256 or even SHA512.
//!
//! ## Traits
//!
//! - `Payload`: A trait for data structures that can be signed and verified.
//!
//! ## Errors
//!
//! Errors are represented by the `Error` enum, which includes:
//!
//! - `InvalidInput`: Invalid input payload.
//! - `InvalidSignature`: Invalid signature provided.
//! - `InvalidPayload`: Invalid payload structure when de-serialising valid payload
//! - `InvalidToken`: Invalid token provided.
//! - `HkdfExpandError`: Error during key expansion.
//! - `HkdfFillError`: Error during key filling.
//! - `TokenExpired`: Token has expired.
//!
//! ## Contributing
//!
//! Contributions are welcome! Feel free to open issues and pull requests on [GitHub](https://github.com/KJHJason/hmac-serialiser/tree/master/rust).
//!
//! ```

pub mod algorithm;
pub mod errors;
pub mod hkdf;

use base64::{engine::general_purpose, Engine as _};
use serde::{Deserialize, Serialize};

pub use algorithm::Algorithm;
pub use errors::Error;

#[cfg(not(feature = "ring"))]
use hmac::Mac;

#[cfg(feature = "ring")]
use ring::hmac;

pub const DELIM: char = '.';

/// An enum for defining the encoding scheme for the payload and the signature.
///
/// Usually, you should use the encoder with no padding to shorten the token length by a few characters.
///
/// Whether to use URL-safe or Standard encoding depends on the application's requirements.
///
/// For example, if you are developing a password reset route
/// in a web application like /password-reset?token=...., you would want
/// to use the UrlSafe encoding so that the token can be safely used in the URL.
#[derive(Default, Debug, Clone)]
pub enum Encoder {
    // Standard base64 encoding
    Standard,

    // URL-safe base64 encoding
    UrlSafe,

    // Standard base64 encoding without padding
    StandardNoPadding,

    #[default]
    // URL-safe base64 encoding without padding
    UrlSafeNoPadding,
}

impl Encoder {
    #[inline]
    fn get_encoder(&self) -> general_purpose::GeneralPurpose {
        match self {
            Encoder::Standard => general_purpose::STANDARD,
            Encoder::UrlSafe => general_purpose::URL_SAFE,
            Encoder::StandardNoPadding => general_purpose::STANDARD_NO_PAD,
            Encoder::UrlSafeNoPadding => general_purpose::URL_SAFE_NO_PAD,
        }
    }
}

/// A trait for custom payload types that can be signed and verified.
///
/// This trait defines methods for retrieving expiration time and is used in conjunction with
/// signing and verifying operations.
///
/// If your payload type does not require an expiration time, you can implement the trait as follows:
/// ```rust
/// use hmac_serialiser::Payload;
/// use chrono::{DateTime, Utc};
///
/// struct CustomData {
///    data: String,
/// }
///
/// impl Payload for CustomData {
///    fn get_exp(&self) -> Option<DateTime<Utc>> {
///       None
///   }
/// }
///```
pub trait Payload {
    fn get_exp(&self) -> Option<chrono::DateTime<chrono::Utc>>;
}

/// A struct that holds the key information required for key expansion.
///
/// The key expansion process is used to derive a new key from the main secret key. Its main purpose is to expand
/// the key to the HMAC algorithm's block size to avoid padding which can reduce the effort required for a brute force attack.
///
/// The `KeyInfo` struct contains the main secret key, salt for key expansion, and optional application-specific info.
/// - `key` field is the main secret key used for signing and verifying the payload.
/// - `salt` field is used for key expansion.
/// - `info` field is optional and can be used to provide application-specific information.
///
/// The `salt` and the `info` fields can help to prevent key reuse and provide additional security.
#[derive(Debug, Clone)]
pub struct KeyInfo {
    // Main secret key
    pub key: Vec<u8>,

    // Salt for the key expansion (Optional)
    pub salt: Vec<u8>,

    // Application specific info (Optional)
    pub info: Vec<u8>,
}

impl Default for KeyInfo {
    fn default() -> Self {
        Self {
            key: vec![],
            salt: vec![],
            info: vec![],
        }
    }
}

/// A struct that holds the HMAC signer logic.
///
/// The `HmacSigner` struct is used for signing and verifying the payload using HMAC signatures.
#[derive(Debug, Clone)]
pub struct HmacSigner {
    #[cfg(not(feature = "ring"))]
    expanded_key: Vec<u8>,
    #[cfg(not(feature = "ring"))]
    algo: Algorithm,
    #[cfg(feature = "ring")]
    expanded_key: hmac::Key,

    encoder: general_purpose::GeneralPurpose,
}

#[cfg(not(feature = "ring"))]
macro_rules! get_hmac {
    ($self:ident, $D:ty) => {
        hmac::Hmac::<$D>::new_from_slice(&$self.expanded_key)
            .expect("HMAC can take key of any size")
    };
}

#[cfg(not(feature = "ring"))]
macro_rules! hmac_sign {
    ($self:ident, $payload:ident, $D:ty) => {{
        let mut mac = get_hmac!($self, $D);
        mac.update($payload);
        mac.finalize().into_bytes().to_vec()
    }};
}

#[cfg(not(feature = "ring"))]
macro_rules! hmac_verify {
    ($self:ident, $payload:ident, $signature:ident, $D:ty) => {{
        let mut mac = get_hmac!($self, $D);
        mac.update($payload);
        mac.verify_slice($signature).is_ok()
    }};
}

impl HmacSigner {
    pub fn new(key_info: KeyInfo, algo: Algorithm, encoder: Encoder) -> Self {
        if key_info.key.is_empty() {
            panic!("Key cannot be empty"); // panic if key is empty as it is usually due to developer error
        }

        let expanded_key = hkdf::HkdfWrapper::new(algo.clone()).expand(
            &key_info.key,
            &key_info.salt,
            &key_info.info,
        );

        #[cfg(feature = "ring")]
        {
            let expanded_key = hmac::Key::new(algo.to_hmac(), &expanded_key);
            return Self {
                expanded_key,
                encoder: encoder.get_encoder(),
            };
        }
        #[cfg(not(feature = "ring"))]
        Self {
            expanded_key,
            algo,
            encoder: encoder.get_encoder(),
        }
    }

    #[inline]
    #[cfg(not(feature = "ring"))]
    fn sign_payload(&self, payload: &[u8]) -> Vec<u8> {
        match self.algo {
            Algorithm::SHA1 => hmac_sign!(self, payload, sha1::Sha1),
            Algorithm::SHA256 => hmac_sign!(self, payload, sha2::Sha256),
            Algorithm::SHA384 => hmac_sign!(self, payload, sha2::Sha384),
            Algorithm::SHA512 => hmac_sign!(self, payload, sha2::Sha512),
        }
    }

    #[inline]
    #[cfg(not(feature = "ring"))]
    fn verify(&self, payload: &[u8], signature: &[u8]) -> bool {
        match self.algo {
            Algorithm::SHA1 => hmac_verify!(self, payload, signature, sha1::Sha1),
            Algorithm::SHA256 => hmac_verify!(self, payload, signature, sha2::Sha256),
            Algorithm::SHA384 => hmac_verify!(self, payload, signature, sha2::Sha384),
            Algorithm::SHA512 => hmac_verify!(self, payload, signature, sha2::Sha512),
        }
    }

    #[inline]
    #[cfg(feature = "ring")]
    fn sign_payload(&self, payload: &[u8]) -> Vec<u8> {
        hmac::sign(&self.expanded_key, payload).as_ref().to_vec()
    }

    #[inline]
    #[cfg(feature = "ring")]
    fn verify(&self, payload: &[u8], signature: &[u8]) -> bool {
        hmac::verify(&self.expanded_key, payload, signature).is_ok()
    }
}

impl HmacSigner {
    /// Verifies the token and returns the deserialised payload.
    ///
    /// Before verifying the payload, the input token is split into two parts: the encoded payload and the signature.
    /// If the token does not contain two parts, an `InvalidInput` error is returned.
    ///
    /// Afterwards, if the encoded payload is empty, an `InvalidToken` error is returned even if the signature is valid.
    ///
    /// The signature is then decoded using the provided encoder. If the decoding fails, an `InvalidSignature` error is returned.
    ///
    /// The encoded payload and the signature are then verified via HMAC. If the verification fails, an `InvalidToken` error is returned.
    ///
    /// If the encoded payload is valid, the payload is decoded and deserialised using serde.
    /// If the payload's expiration time is not provided, the deserialized payload is returned.
    /// Otherwise, the expiration time is checked against the current time. If the expiration time is earlier than the current time, a `TokenExpired` error is returned.
    ///
    /// Sample Usage:
    /// ```rust
    /// use hmac_serialiser::{HmacSigner, KeyInfo, Encoder, algorithm::Algorithm, Error, Payload};
    /// use serde::{Serialize, Deserialize};
    ///
    /// #[derive(Serialize, Deserialize, Debug)]
    /// struct UserData {
    ///     username: String,
    /// }
    /// impl Payload for UserData {
    ///    fn get_exp(&self) -> Option<chrono::DateTime<chrono::Utc>> {
    ///         None
    ///     }
    /// }
    ///
    /// let key_info = KeyInfo {
    ///    key: b"your_secret_key".to_vec(),
    ///    salt: b"your_salt".to_vec(),
    ///    info: vec![], // empty info
    /// };
    ///
    /// // Initialize the HMAC signer
    /// let signer = HmacSigner::new(key_info, Algorithm::SHA256, Encoder::UrlSafe);
    /// let result: Result<UserData, Error> = signer.unsign(&"token.signature");
    /// // or
    /// let result = signer.unsign::<UserData>(&"token.signature");
    /// ```
    pub fn unsign<T: for<'de> Deserialize<'de> + Payload>(&self, token: &str) -> Result<T, Error> {
        let parts: Vec<&str> = token.split(DELIM).collect();
        if parts.len() != 2 {
            return Err(Error::InvalidInput(token.to_string()));
        }

        let encoded_payload = parts[0];
        if encoded_payload.is_empty() {
            return Err(Error::InvalidToken);
        }

        let signature = self
            .encoder
            .decode(parts[1])
            .map_err(|_| Error::InvalidSignature)?;
        let encoded_payload = parts[0].as_bytes();
        if !self.verify(&encoded_payload, &signature) {
            return Err(Error::InvalidToken);
        }

        // at this pt, the token is valid and hence we can safely unwrap
        let decoded_payload = self
            .encoder
            .decode(encoded_payload)
            .expect("payload should be valid base64");
        let payload = String::from_utf8(decoded_payload).expect("payload should be valid utf-8");

        // usually de-serialisation errors are
        // caused when the developer was expecting the
        // wrong payload type or has recently changed the payload type
        let deserialised_payload: T =
            serde_json::from_str(&payload).map_err(|_| Error::InvalidPayload)?;

        if let Some(expiry) = deserialised_payload.get_exp() {
            if expiry < chrono::Utc::now() {
                return Err(Error::TokenExpired);
            }
        }
        Ok(deserialised_payload)
    }

    /// Signs the payload and returns the token which can be sent to the client.
    ///
    /// Sample Usage:
    /// ```rust
    /// use hmac_serialiser::{HmacSigner, KeyInfo, Encoder, algorithm::Algorithm, Error, Payload};
    /// use serde::{Serialize, Deserialize};
    ///
    /// #[derive(Serialize, Deserialize, Debug)]
    /// struct UserData {
    ///     username: String,
    /// }
    /// impl Payload for UserData {
    ///    fn get_exp(&self) -> Option<chrono::DateTime<chrono::Utc>> {
    ///         None
    ///     }
    /// }
    ///
    /// let key_info = KeyInfo {
    ///    key: b"your_secret_key".to_vec(),
    ///    salt: b"your_salt".to_vec(),
    ///    info: b"auth-context".to_vec(),
    /// };
    ///
    /// // Initialize the HMAC signer
    /// let signer = HmacSigner::new(key_info, Algorithm::SHA256, Encoder::UrlSafe);
    /// let user = UserData { username: "user123".to_string() };
    /// let result: String = signer.sign(&user);
    /// ```
    pub fn sign<T: Serialize + Payload>(&self, payload: &T) -> String {
        let token = serde_json::to_string(payload).unwrap();
        let token = self.encoder.encode(token.as_bytes());
        let signature = self.sign_payload(token.as_bytes());
        let signature = self.encoder.encode(&signature);
        format!("{}{}{}", token, DELIM, signature)
    }
}