use super::Signer;
use crate::error::{GarrisonError, GarrisonResult};
use base64::{engine::general_purpose::STANDARD, Engine};
use hmac::{Hmac, KeyInit, Mac};
use sha2::{Sha256, Sha512};
fn hex_encode(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{:02x}", b)).collect()
}
impl Signer {
pub fn hmac_sha256(secret: &[u8], data: &[u8]) -> String {
type HmacSha256 = Hmac<Sha256>;
let mut mac = HmacSha256::new_from_slice(secret).expect("HMAC accepts any key length");
mac.update(data);
hex_encode(&mac.finalize().into_bytes())
}
pub fn verify_hmac_sha256(secret: &[u8], data: &[u8], expected_sig: &str) -> bool {
type HmacSha256 = Hmac<Sha256>;
let mut mac = HmacSha256::new_from_slice(secret).expect("HMAC accepts any key length");
mac.update(data);
let computed_hex = hex_encode(&mac.finalize().into_bytes());
#[cfg(feature = "subtle")]
{
use subtle::ConstantTimeEq;
let a = computed_hex.as_bytes();
let b = expected_sig.as_bytes();
let len_eq = (a.len() as u64).ct_eq(&(b.len() as u64));
let max_len = a.len().max(b.len());
let mut byte_eq = subtle::Choice::from(1);
for i in 0..max_len {
let x = a.get(i).copied().unwrap_or(0);
let y = b.get(i).copied().unwrap_or(0);
byte_eq &= x.ct_eq(&y);
}
(len_eq & byte_eq).unwrap_u8() == 1
}
#[cfg(not(feature = "subtle"))]
{
constant_time_eq_manual(computed_hex.as_bytes(), expected_sig.as_bytes())
}
}
pub fn hmac_sha512(secret: &[u8], data: &[u8]) -> String {
type HmacSha512 = Hmac<Sha512>;
let mut mac = HmacSha512::new_from_slice(secret).expect("HMAC accepts any key length");
mac.update(data);
hex_encode(&mac.finalize().into_bytes())
}
pub fn base64_encode(data: &[u8]) -> String {
STANDARD.encode(data)
}
pub fn base64_decode(s: &str) -> GarrisonResult<Vec<u8>> {
STANDARD
.decode(s)
.map_err(|e| GarrisonError::Internal(format!("secure-base64-decode::{}", e)))
}
#[deprecated(note = "MD5 已不安全,请使用 hmac_sha256 或 hmac_sha512")]
pub fn md5(data: &[u8]) -> String {
let digest = md5::compute(data);
hex_encode(&digest.0)
}
}
#[cfg(not(feature = "subtle"))]
fn constant_time_eq_manual(a: &[u8], b: &[u8]) -> bool {
let max_len = a.len().max(b.len());
let mut diff: u8 = if a.len() != b.len() { 0xff } else { 0 };
for i in 0..max_len {
let x = a.get(i).copied().unwrap_or(0);
let y = b.get(i).copied().unwrap_or(0);
diff |= x ^ y;
}
diff == 0
}