microsandbox_core/utils/
file.rs1use std::path::Path;
4
5use oci_spec::image::DigestAlgorithm;
6use sha2::{Digest, Sha256, Sha384, Sha512};
7use tokio::{fs::File, io::AsyncReadExt};
8
9use crate::{MicrosandboxError, MicrosandboxResult};
10
11pub async fn get_file_hash(
17 path: &Path,
18 algorithm: &DigestAlgorithm,
19) -> MicrosandboxResult<Vec<u8>> {
20 let mut file = File::open(path).await?;
21 let mut buffer = Vec::new();
22 file.read_to_end(&mut buffer).await?;
23
24 let hash = match algorithm {
25 DigestAlgorithm::Sha256 => Sha256::digest(&buffer).to_vec(),
26 DigestAlgorithm::Sha384 => Sha384::digest(&buffer).to_vec(),
27 DigestAlgorithm::Sha512 => Sha512::digest(&buffer).to_vec(),
28 _ => {
29 return Err(MicrosandboxError::UnsupportedImageHashAlgorithm(format!(
30 "Unsupported algorithm: {}",
31 algorithm
32 )));
33 }
34 };
35
36 Ok(hash)
37}