use crate::{ManicError, Result};
use derive_more::Display;
use md5::Md5;
use sha2::Digest;
use sha2::{Sha224, Sha256, Sha384, Sha512};
use tracing::debug;
#[derive(Debug, Clone, Display)]
pub enum Hash {
#[display(fmt = "{}", "_1")]
MD5(Md5, String),
#[display(fmt = "{}", "_1")]
SHA224(Sha224, String),
#[display(fmt = "{}", "_1")]
SHA256(Sha256, String),
#[display(fmt = "{}", "_1")]
SHA384(Sha384, String),
#[display(fmt = "{}", "_1")]
SHA512(Sha512, String),
}
impl Hash {
pub fn new_sha224(to_verify: String) -> Self {
Self::SHA224(Sha224::new(), to_verify)
}
pub fn new_sha256(to_verify: String) -> Self {
Self::SHA256(Sha256::new(), to_verify)
}
pub fn new_sha384(to_verify: String) -> Self {
Self::SHA384(Sha384::new(), to_verify)
}
pub fn new_sha512(to_verify: String) -> Self {
Self::SHA512(Sha512::new(), to_verify)
}
pub fn finalize(self) -> String {
match self {
Self::SHA256(h, _) => format!("{:x}", h.finalize()),
Self::SHA224(h, _) => format!("{:x}", h.finalize()),
Self::SHA512(h, _) => format!("{:x}", h.finalize()),
Self::SHA384(h, _) => format!("{:x}", h.finalize()),
Self::MD5(h, _) => format!("{:x}", h.finalize()),
}
}
pub fn verify(self) -> Result<()> {
let hash_string = format!("{}", self);
debug!("Comparing sum {}", hash_string);
let to_verify = self.finalize();
debug!("SHA256 sum: {}", to_verify);
if to_verify == hash_string {
debug!("SHAsum match!");
Ok(())
} else {
Err(ManicError::SHA256MisMatch(to_verify))
}
}
pub fn update(&mut self, data: &[u8]) {
match self {
Self::SHA256(h, _) => h.update(data),
Self::SHA224(h, _) => h.update(data),
Self::SHA384(h, _) => h.update(data),
Self::SHA512(h, _) => h.update(data),
Self::MD5(h, _) => h.update(data),
}
}
}