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
use lazy_static::lazy_static;
use md5::{Digest, Md5};
use regex::Regex;
lazy_static! {
static ref RE: Regex = Regex::new("\x40generated (?:SignedSource<<([a-f0-9]{32})>>)").unwrap();
}
fn hash(data: &str) -> String {
let mut hasher = Md5::new();
hasher.update(data);
hex::encode(hasher.finalize())
}
fn sign(data: &str) -> String {
data.replace(NEWTOKEN, &format!("SignedSource<<{}>>", hash(data)))
}
pub const NEWTOKEN: &str = "<<SignedSource::*O*zOeWoEQle#+L!plEphiEmie\x40IsG>>";
pub const SIGNING_TOKEN: &str = "\x40generated <<SignedSource::*O*zOeWoEQle#+L!plEphiEmie\x40IsG>>";
pub fn is_signed(data: &str) -> bool {
RE.is_match(data)
}
pub fn sign_file(data: &str) -> String {
try_sign_file(data).unwrap_or_else(|| {
panic!(
"sign_file(...): Cannot sign file without token {}",
NEWTOKEN
)
})
}
pub fn try_sign_file(data: &str) -> Option<String> {
if data.contains(NEWTOKEN) {
Some(sign(data))
} else {
None
}
}
pub fn is_valid_signature(data: &str) -> bool {
if let Some(mat) = RE.find(data) {
let actual = &data[mat.start() + 25..mat.end() - 2];
let unsigned = RE.replace(data, SIGNING_TOKEN);
return hash(&unsigned) == actual;
}
false
}
#[cfg(test)]
mod tests;