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
use crate::{INITIAL_STATE, MD5};
use std::{fs::File, io::Read};
pub trait Digest {
fn reset(&mut self) -> &mut Self;
fn update(&mut self, value: &[u8]) -> &mut Self;
fn update_file(&mut self, path: &str) -> &mut Self;
fn hexdigest(value: &str) -> String;
fn hexdigest_file(path: &str) -> String;
fn reset_file(&mut self, path: &str) -> &mut Self;
}
impl Digest for MD5 {
fn reset(&mut self) -> &mut Self {
self.state = INITIAL_STATE;
self.count.fill(0);
self.buffer.fill(0);
self.digest.fill(0);
self
}
fn update(&mut self, value: &[u8]) -> &mut Self {
self.update_with_len(value, value.len())
}
fn update_file(&mut self, path: &str) -> &mut Self {
let mut file = File::open(path).expect("Couldn't open file");
let mut buffer = [0; 1024];
loop {
let nbytes = file.read(&mut buffer).expect("Couldn't read file");
if nbytes == 0 {
break;
}
self.update_with_len(&buffer, nbytes);
}
self
}
fn hexdigest(value: &str) -> String {
Self::new().update(value.as_bytes()).finalize().to_string()
}
fn hexdigest_file(path: &str) -> String {
let mut file = File::open(path).expect("Couldn't open file");
let mut buffer = [0; 1024];
let mut mdg = Self::new();
loop {
let nbytes = file.read(&mut buffer).expect("Couldn't read file");
if nbytes == 0 {
break;
}
mdg.update_with_len(&buffer, nbytes);
}
mdg.finalize().to_string()
}
fn reset_file(&mut self, path: &str) -> &mut Self {
self.reset();
self.update_file(path)
}
}