1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
use anyhow::Result;
use ring::digest::{Context, SHA1_FOR_LEGACY_USE_ONLY, SHA256, SHA384, SHA512};
use std::fmt::Write;
use std::{io::Read, path::Path};

pub fn blake3(file_path: &Path) -> Result<String> {
    let mut file = std::fs::File::open(file_path)?;
    let mut hasher = blake3::Hasher::new();
    let mut buf = [0_u8; 65536];
    while let Ok(size) = file.read(&mut buf[..]) {
        if size == 0 {
            break;
        }
        hasher.update(&buf[0..size]);
    }
    Ok(hasher.finalize().to_hex().to_string())
}

pub fn md5(file_path: &Path) -> Result<String> {
    let mut file = std::fs::File::open(file_path)?;
    let mut context = md5::Context::new();
    let mut buf = [0_u8; 65536];
    while let Ok(size) = file.read(&mut buf[..]) {
        if size == 0 {
            break;
        }
        context.consume(&buf[0..size]);
    }
    Ok(write_hex_bytes(context.compute().as_ref()))
}

pub fn sha1(file_path: &Path) -> Result<String> {
    let mut file = std::fs::File::open(file_path)?;
    let mut context = Context::new(&SHA1_FOR_LEGACY_USE_ONLY);
    let mut buf = [0_u8; 65536];
    while let Ok(size) = file.read(&mut buf[..]) {
        if size == 0 {
            break;
        }
        context.update(&buf[0..size]);
    }
    Ok(write_hex_bytes(context.finish().as_ref()))
}

pub fn sha256(file_path: &Path) -> Result<String> {
    let mut file = std::fs::File::open(file_path)?;
    let mut context = Context::new(&SHA256);
    let mut buf = [0_u8; 65536];
    while let Ok(size) = file.read(&mut buf[..]) {
        if size == 0 {
            break;
        }
        context.update(&buf[0..size]);
    }
    Ok(write_hex_bytes(context.finish().as_ref()))
}

pub fn sha384(file_path: &Path) -> Result<String> {
    let mut file = std::fs::File::open(file_path)?;
    let mut context = Context::new(&SHA384);
    let mut buf = [0_u8; 65536];
    while let Ok(size) = file.read(&mut buf[..]) {
        if size == 0 {
            break;
        }
        context.update(&buf[0..size]);
    }
    Ok(write_hex_bytes(context.finish().as_ref()))
}

pub fn sha512(file_path: &Path) -> Result<String> {
    let mut file = std::fs::File::open(file_path)?;
    let mut context = Context::new(&SHA512);
    let mut buf = [0_u8; 65536];
    while let Ok(size) = file.read(&mut buf[..]) {
        if size == 0 {
            break;
        }
        context.update(&buf[0..size]);
    }
    Ok(write_hex_bytes(context.finish().as_ref()))
}

pub fn write_hex_bytes(bytes: &[u8]) -> String {
    let mut s = String::new();
    for byte in bytes {
        write!(&mut s, "{byte:02x}").expect("Unable to write");
    }
    s
}