yubihsm/hmac/
algorithm.rs

1//! HMAC algorithms
2
3use crate::algorithm;
4
5/// Valid algorithms for HMAC keys
6#[derive(Copy, Clone, Debug, Eq, PartialEq)]
7#[repr(u8)]
8pub enum Algorithm {
9    /// `hmac-sha1`
10    Sha1 = 0x13,
11
12    /// `hmac-sha256`
13    Sha256 = 0x14,
14
15    /// `hmac-sha384`
16    Sha384 = 0x15,
17
18    /// `hmac-sha512`
19    Sha512 = 0x16,
20}
21
22impl Algorithm {
23    /// Convert an unsigned byte tag into an `Algorithm` (if valid)
24    pub fn from_u8(tag: u8) -> Result<Self, algorithm::Error> {
25        Ok(match tag {
26            0x13 => Algorithm::Sha1,
27            0x14 => Algorithm::Sha256,
28            0x15 => Algorithm::Sha384,
29            0x16 => Algorithm::Sha512,
30            _ => fail!(
31                algorithm::ErrorKind::TagInvalid,
32                "unknown HMAC algorithm ID: 0x{:02x}",
33                tag
34            ),
35        })
36    }
37
38    /// Serialize algorithm ID as a byte
39    pub fn to_u8(self) -> u8 {
40        self as u8
41    }
42
43    /// Recommended key length (identical to output size)
44    pub fn key_len(self) -> usize {
45        match self {
46            Algorithm::Sha1 => 20,
47            Algorithm::Sha256 => 32,
48            Algorithm::Sha384 => 48,
49            Algorithm::Sha512 => 64,
50        }
51    }
52
53    /// Return the size of the given key (as expected by the `YubiHSM 2`) in bytes
54    pub fn max_key_len(self) -> usize {
55        match self {
56            Algorithm::Sha1 => 64,
57            Algorithm::Sha256 => 64,
58            Algorithm::Sha384 => 128,
59            Algorithm::Sha512 => 128,
60        }
61    }
62}
63
64impl_algorithm_serializers!(Algorithm);