hmac/
utils.rs

1use digest::{
2    Digest,
3    block_api::{Block, BlockSizeUser},
4};
5
6pub(crate) const IPAD: u8 = 0x36;
7pub(crate) const OPAD: u8 = 0x5C;
8
9pub(crate) fn get_der_key<D: Digest + BlockSizeUser>(key: &[u8]) -> Block<D> {
10    let mut der_key = Block::<D>::default();
11    // The key that HMAC processes must be the same as the block size of the
12    // underlying hash function. If the provided key is smaller than that,
13    // we just pad it with zeros. If its larger, we hash it and then pad it
14    // with zeros.
15    if key.len() <= der_key.len() {
16        der_key[..key.len()].copy_from_slice(key);
17    } else {
18        let hash = D::digest(key);
19        // All commonly used hash functions have block size bigger
20        // than output hash size, but to be extra rigorous we
21        // handle the potential uncommon cases as well.
22        // The condition is calculated at compile time, so this
23        // branch gets removed from the final binary.
24        if hash.len() <= der_key.len() {
25            der_key[..hash.len()].copy_from_slice(&hash);
26        } else {
27            let n = der_key.len();
28            der_key.copy_from_slice(&hash[..n]);
29        }
30    }
31    der_key
32}