use super::DigestAlgorithm;
use crate::error::{GarrisonError, GarrisonResult};
use std::str::FromStr;
pub(super) fn hex_encode(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{:02x}", b)).collect()
}
impl DigestAlgorithm {
pub fn as_str(&self) -> &'static str {
match self {
Self::Md5 => "MD5",
Self::Sha256 => "SHA256",
}
}
pub(super) fn hash(&self, data: &[u8]) -> String {
match self {
Self::Md5 => {
let digest = md5::compute(data);
hex_encode(&digest.0)
},
Self::Sha256 => {
use sha2::Digest;
let mut hasher = sha2::Sha256::new();
hasher.update(data);
hex_encode(&hasher.finalize())
},
}
}
}
impl Default for DigestAlgorithm {
fn default() -> Self {
Self::Sha256
}
}
impl FromStr for DigestAlgorithm {
type Err = GarrisonError;
fn from_str(s: &str) -> GarrisonResult<Self> {
match s.to_ascii_uppercase().as_str() {
"MD5" => Ok(Self::Md5),
"SHA256" => Ok(Self::Sha256),
other => Err(GarrisonError::Internal(format!(
"digest-algo-unsupported::{}",
other
))),
}
}
}