use crate::encoding::bytes_from_b64;
use sha2::{Digest, Sha256, Sha384, Sha512};
#[derive(Clone, Copy, Debug)]
pub enum SriAlgorithm {
Sha256,
Sha384,
Sha512,
}
impl SriAlgorithm {
fn strength(self) -> u8 {
match self {
SriAlgorithm::Sha256 => 1,
SriAlgorithm::Sha384 => 2,
SriAlgorithm::Sha512 => 3,
}
}
fn hash(self, data: &[u8]) -> Vec<u8> {
match self {
SriAlgorithm::Sha256 => Sha256::digest(data).to_vec(),
SriAlgorithm::Sha384 => Sha384::digest(data).to_vec(),
SriAlgorithm::Sha512 => Sha512::digest(data).to_vec(),
}
}
}
#[derive(Debug)]
pub struct SriEntry {
pub algorithm: SriAlgorithm,
pub expected: Vec<u8>,
}
pub fn parse_integrity(input: &str) -> Vec<SriEntry> {
let mut out = Vec::new();
for token in input.split_ascii_whitespace() {
let (algo_hash, _opts) = match token.split_once('?') {
Some((a, o)) => (a, Some(o)),
None => (token, None),
};
let Some((algo, hash_b64)) = algo_hash.split_once('-') else {
continue;
};
let algorithm = match algo {
"sha256" => SriAlgorithm::Sha256,
"sha384" => SriAlgorithm::Sha384,
"sha512" => SriAlgorithm::Sha512,
_ => continue,
};
let normalized: String = hash_b64
.chars()
.map(|c| match c {
'-' => '+',
'_' => '/',
c => c,
})
.collect();
let Ok(expected) = bytes_from_b64(normalized.as_bytes()) else {
continue;
};
out.push(SriEntry {
algorithm,
expected,
});
}
out
}
pub fn verify(entries: &[SriEntry], data: &[u8]) -> bool {
if entries.is_empty() {
return true;
}
let strongest = entries
.iter()
.map(|e| e.algorithm.strength())
.max()
.unwrap();
for entry in entries {
if entry.algorithm.strength() != strongest {
continue;
}
let actual = entry.algorithm.hash(data);
if actual == entry.expected {
return true;
}
}
false
}