Skip to main content

AirLibrary/Updates/
ChecksumUtil.rs

1#![allow(unused_variables, dead_code, unused_imports)]
2
3//! Standalone checksum calculation helpers for update integrity verification.
4//!
5//! These free functions mirror the private methods on `UpdateManager` so the
6//! same hashing logic can be unit-tested without constructing a full manager
7//! and can be reused by other modules (e.g. Downloader) without cross-crate
8//! duplication.
9
10use sha2::{Digest, Sha256, Sha512};
11
12/// SHA-256 hex digest of `data`.
13pub fn sha256_hex(data:&[u8]) -> String {
14	let mut h = Sha256::new();
15	h.update(data);
16	hex::encode(h.finalize())
17}
18
19/// SHA-512 hex digest of `data`.
20pub fn sha512_hex(data:&[u8]) -> String {
21	let mut h = Sha512::new();
22	h.update(data);
23	hex::encode(h.finalize())
24}
25
26/// MD5 hex digest of `data`.
27pub fn md5_hex(data:&[u8]) -> String {
28	let digest = md5::compute(data);
29	format!("{:x}", digest)
30}
31
32/// CRC-32 hex digest of `data` (8 hex digits, zero-padded).
33pub fn crc32_hex(data:&[u8]) -> String {
34	let crc = crc32fast::hash(data);
35	format!("{:08x}", crc)
36}
37
38/// SHA-256 hex digest of a file at `path`.
39pub async fn sha256_file(path:&std::path::Path) -> Result<String, std::io::Error> {
40	let content = tokio::fs::read(path).await?;
41	Ok(sha256_hex(&content))
42}
43
44/// Verify `data` against an expected hex digest using the named algorithm.
45/// Supported algorithms: `sha256`, `sha512`, `md5`, `crc32`.
46/// Returns `true` on match, `false` on mismatch or unknown algorithm.
47pub fn verify(data:&[u8], algorithm:&str, expected:&str) -> bool {
48	let actual = match algorithm.to_lowercase().as_str() {
49		"sha256" => sha256_hex(data),
50		"sha512" => sha512_hex(data),
51		"md5" => md5_hex(data),
52		"crc32" => crc32_hex(data),
53		_ => return false,
54	};
55	actual == expected
56}