Skip to main content

AirLibrary/Updates/
ChecksumUtil.rs

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