32 lines
849 B
Rust
32 lines
849 B
Rust
use std::fs;
|
|
use sha2::{ Digest, Sha256 };
|
|
|
|
quick_error! {
|
|
#[derive(Debug)]
|
|
pub enum DigestError {
|
|
FileOpenError(f: String, m: String) {
|
|
display("Read file: {}, failed: {}", f, m)
|
|
}
|
|
}
|
|
}
|
|
|
|
// pub type XResult<T> = Result<T, Box<dyn std::error::Error>>;
|
|
|
|
pub fn digest_file_sha256(file: &str) -> Result<Vec<u8>, DigestError> {
|
|
let bs = match fs::read(file) {
|
|
Ok(bs) => bs, Err(e) => return Err(DigestError::FileOpenError(file.into(), e.to_string())),
|
|
};
|
|
Ok(digest_sha256(&bs))
|
|
}
|
|
|
|
pub fn digest_sha256(bs: &[u8]) -> Vec<u8> {
|
|
let mut sha256 = Sha256::new();
|
|
sha256.update(bs);
|
|
sha256.finalize().to_vec()
|
|
}
|
|
|
|
#[test]
|
|
fn test_digest_sha256() {
|
|
assert_eq!(hex::decode("b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9").unwrap(), digest_sha256(b"hello world"));
|
|
}
|