Skip to main content

yosh_plugin_manager/
verify.rs

1use std::path::Path;
2
3use sha2::{Digest, Sha256};
4
5/// Compute the SHA-256 hex digest of a file.
6pub fn sha256_file(path: &Path) -> Result<String, String> {
7    let data = std::fs::read(path).map_err(|e| format!("{}: {}", path.display(), e))?;
8    let hash = Sha256::digest(&data);
9    Ok(format!("{:x}", hash))
10}
11
12/// Check if a file's SHA-256 matches the expected hex digest.
13pub fn verify_checksum(path: &Path, expected: &str) -> Result<bool, String> {
14    let actual = sha256_file(path)?;
15    Ok(actual == expected)
16}
17
18#[cfg(test)]
19mod tests {
20    use super::*;
21    use std::io::Write;
22
23    #[test]
24    fn sha256_known_content() {
25        let mut f = tempfile::NamedTempFile::new().unwrap();
26        f.write_all(b"hello world").unwrap();
27        let hash = sha256_file(f.path()).unwrap();
28        assert_eq!(
29            hash,
30            "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"
31        );
32    }
33
34    #[test]
35    fn sha256_empty_file() {
36        let f = tempfile::NamedTempFile::new().unwrap();
37        let hash = sha256_file(f.path()).unwrap();
38        assert_eq!(
39            hash,
40            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
41        );
42    }
43
44    #[test]
45    fn sha256_missing_file() {
46        assert!(sha256_file(Path::new("/nonexistent/file")).is_err());
47    }
48
49    #[test]
50    fn verify_checksum_match() {
51        let mut f = tempfile::NamedTempFile::new().unwrap();
52        f.write_all(b"hello world").unwrap();
53        assert!(
54            verify_checksum(
55                f.path(),
56                "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"
57            )
58            .unwrap()
59        );
60    }
61
62    #[test]
63    fn verify_checksum_mismatch() {
64        let mut f = tempfile::NamedTempFile::new().unwrap();
65        f.write_all(b"hello world").unwrap();
66        assert!(
67            !verify_checksum(
68                f.path(),
69                "0000000000000000000000000000000000000000000000000000000000000000"
70            )
71            .unwrap()
72        );
73    }
74}