http-signature-normalization/http-signature-normalization-actix/src/digest/sha2.rs
asonix aaf8e16db4 Add basic digest logging
handle differing digest name cases
2020-03-17 14:28:04 -05:00

121 lines
3.1 KiB
Rust

use log::{info, warn};
use sha2::{Sha224, Sha256, Sha384, Sha512, Sha512Trunc224, Sha512Trunc256};
use super::{DigestCreate, DigestPart, DigestVerify};
fn create(digest: &mut impl sha2::Digest, input: &[u8]) -> String {
digest.input(input);
base64::encode(&digest.result_reset())
}
fn verify(digest: &mut impl sha2::Digest, name: &str, parts: &[DigestPart], bytes: &[u8]) -> bool {
if let Some(part) = parts
.iter()
.find(|p| p.algorithm.to_lowercase() == name.to_lowercase())
{
info!("Verifying digest type, {}", name);
digest.input(bytes);
let encoded = base64::encode(&digest.result_reset());
return part.digest == encoded;
}
warn!("No matching digest algorithm found for {}", name);
warn!(
"Provided: [{}]",
parts.iter().fold(String::new(), |mut acc, item| {
if acc.is_empty() {
} else {
acc.extend(", ".chars());
}
acc.extend(item.algorithm.chars());
acc
})
);
false
}
impl DigestCreate for Sha224 {
const NAME: &'static str = "SHA-224";
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
}
impl DigestVerify for Sha224 {
fn verify(&mut self, parts: &[DigestPart], bytes: &[u8]) -> bool {
verify(self, <Self as DigestCreate>::NAME, parts, bytes)
}
}
impl DigestCreate for Sha256 {
const NAME: &'static str = "SHA-256";
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
}
impl DigestVerify for Sha256 {
fn verify(&mut self, parts: &[DigestPart], bytes: &[u8]) -> bool {
verify(self, <Self as DigestCreate>::NAME, parts, bytes)
}
}
impl DigestCreate for Sha384 {
const NAME: &'static str = "SHA-384";
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
}
impl DigestVerify for Sha384 {
fn verify(&mut self, parts: &[DigestPart], bytes: &[u8]) -> bool {
verify(self, <Self as DigestCreate>::NAME, parts, bytes)
}
}
impl DigestCreate for Sha512 {
const NAME: &'static str = "SHA-512";
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
}
impl DigestVerify for Sha512 {
fn verify(&mut self, parts: &[DigestPart], bytes: &[u8]) -> bool {
verify(self, <Self as DigestCreate>::NAME, parts, bytes)
}
}
impl DigestCreate for Sha512Trunc224 {
const NAME: &'static str = "SHA-512-224";
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
}
impl DigestVerify for Sha512Trunc224 {
fn verify(&mut self, parts: &[DigestPart], bytes: &[u8]) -> bool {
verify(self, <Self as DigestCreate>::NAME, parts, bytes)
}
}
impl DigestCreate for Sha512Trunc256 {
const NAME: &'static str = "SHA-512-256";
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
}
impl DigestVerify for Sha512Trunc256 {
fn verify(&mut self, parts: &[DigestPart], bytes: &[u8]) -> bool {
verify(self, <Self as DigestCreate>::NAME, parts, bytes)
}
}