bitwarden_crypto_primitives/rustcrypto/
hmac.rs1use hmac::{KeyInit, Mac};
2
3use crate::hmac::HashAlg;
4
5#[derive(Clone)]
7pub(crate) enum Hmac {
8 Sha1(hmac::Hmac<sha1::Sha1>),
9 Sha256(hmac::Hmac<sha2::Sha256>),
10 Sha384(hmac::Hmac<sha2::Sha384>),
11 Sha512(hmac::Hmac<sha2::Sha512>),
12}
13
14impl Hmac {
15 pub(crate) fn new(alg: HashAlg, key: &[u8]) -> Self {
16 const ANY_LEN: &str = "HMAC accepts any key length";
18 match alg {
19 HashAlg::Sha1 => Self::Sha1(KeyInit::new_from_slice(key).expect(ANY_LEN)),
20 HashAlg::Sha256 => Self::Sha256(KeyInit::new_from_slice(key).expect(ANY_LEN)),
21 HashAlg::Sha384 => Self::Sha384(KeyInit::new_from_slice(key).expect(ANY_LEN)),
22 HashAlg::Sha512 => Self::Sha512(KeyInit::new_from_slice(key).expect(ANY_LEN)),
23 }
24 }
25
26 pub(crate) fn update(&mut self, data: &[u8]) {
27 match self {
28 Self::Sha1(m) => m.update(data),
29 Self::Sha256(m) => m.update(data),
30 Self::Sha384(m) => m.update(data),
31 Self::Sha512(m) => m.update(data),
32 }
33 }
34
35 pub(crate) fn finalize(self) -> Vec<u8> {
36 match self {
37 Self::Sha1(m) => m.finalize().into_bytes().to_vec(),
38 Self::Sha256(m) => m.finalize().into_bytes().to_vec(),
39 Self::Sha384(m) => m.finalize().into_bytes().to_vec(),
40 Self::Sha512(m) => m.finalize().into_bytes().to_vec(),
41 }
42 }
43}