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
#[macro_use]
extern crate failure;
extern crate crypto;
use failure::Error;
pub type Result<T> = ::std::result::Result<T, Error>;
mod blake2b;
mod keccak;
mod sha2;
mod sha3;
#[derive(Debug, Copy, Clone)]
pub enum HashType {
Sha2,
Sha3,
Blake2b,
Keccak,
}
#[derive(Debug, Copy, Clone)]
pub enum HashLen {
Len160,
Len224,
Len256,
Len384,
Len512,
}
pub fn hash(
input: &[u8],
hash_type: Option<HashType>,
len: Option<HashLen>,
hash_round: Option<u8>,
) -> Result<Vec<u8>> {
let hs_type = hash_type.unwrap_or(HashType::Sha3);
let len = len.unwrap_or(HashLen::Len256);
let round = match hash_round {
Some(n) => {
if n < 1 {
1
} else if n > 100 {
100
} else {
n
}
}
None => match hs_type {
HashType::Sha2 => 2,
_ => 1,
},
};
return match hs_type {
HashType::Sha2 => sha2::hash(input, len, round),
HashType::Sha3 => sha3::hash(input, len, round),
HashType::Blake2b => blake2b::hash(input, len, round),
HashType::Keccak => keccak::hash(input, len, round),
};
}
#[test]
fn test_hash() -> Result<()> {
let message = b"hello rust";
let default_hash = hash(message, None, None, None)?;
let sha3_hash = hash(
message,
Some(HashType::Sha3),
Some(HashLen::Len256),
Some(1),
)?;
assert_eq!(sha3_hash, default_hash);
Ok(())
}