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
use super::Error;
use hmac::{Hmac, Mac};
use sha2::{Sha256, Sha512};
use std::fmt;
use std::str::FromStr;
pub const HMAC_SHA256_PRF_NAME: &str = "hmac-sha256";
pub const HMAC_SHA512_PRF_NAME: &str = "hmac-sha512";
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
pub enum Prf {
#[serde(rename = "hmac-sha256")]
HmacSha256,
#[serde(rename = "hmac-sha512")]
HmacSha512,
}
impl Prf {
pub fn hmac(&self, passphrase: &str) -> Hmac<Sha256> {
Hmac::new_varkey(passphrase.as_bytes()).expect("HMAC accepts all key sizes")
}
pub fn hmac512(&self, passphrase: &str) -> Hmac<Sha512> {
Hmac::new_varkey(passphrase.as_bytes()).expect("HMAC accepts all key sizes")
}
}
impl Default for Prf {
fn default() -> Self {
Prf::HmacSha256
}
}
impl FromStr for Prf {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
_ if s == HMAC_SHA256_PRF_NAME => Ok(Prf::HmacSha256),
_ if s == HMAC_SHA512_PRF_NAME => Ok(Prf::HmacSha512),
_ => Err(Error::UnsupportedPrf(s.to_string())),
}
}
}
impl fmt::Display for Prf {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Prf::HmacSha256 => f.write_str(HMAC_SHA256_PRF_NAME),
Prf::HmacSha512 => f.write_str(HMAC_SHA512_PRF_NAME),
}
}
}