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
use crypto::sha3::Sha3;
use crypto::digest::Digest;

pub fn to_bytes(n: u64) -> Vec<u8> {
    let mut n = n;
    let mut v = Vec::new();
    for _i in 0..4{
        v.push((n & 255) as u8);
        n = n >> 8;
    }
    v
}

pub fn hex_to_bytes(string: &str) -> Vec<u8> {
    let mut bytes = Vec::with_capacity(string.len()/2);
    for i in 0..(string.len() / 2) {
        match u8::from_str_radix(&string[2 * i.. 2 * i + 2], 16) {
            Ok(n) => bytes.push(n),
            Err(_) => panic!("Error in hex conversion"),
        }
    }
    bytes
}

pub fn xor(s1: &[u8], s2: &[u8]) -> Vec<u8> {
    s1.iter().zip(s2).map(|(x, y)| x ^ y).collect() 
}


pub fn swap(block: &[u8]) -> Vec<u8> {
    let l = &block[0..32];
    let mut r = (&block[32..]).to_vec();
    r.extend_from_slice(l);
    r
}

pub fn hash(block: &[u8], key: &[u8]) -> Vec<u8> {
    let mut hasher = Sha3::sha3_256();
    let mut round_block = block.to_vec();
    round_block.extend_from_slice(key);
    hasher.input(&round_block);
    hex_to_bytes(&hasher.result_str())
}

#[cfg(test)]
mod test{
    use super::*;
    #[test]
    fn test_to_bytes(){
        assert_eq!(vec![1,0,0,0], to_bytes(1));
        assert_eq!(vec![0,1,0,0], to_bytes(256), "{:?}, {:?}", vec![1,1,0,0], to_bytes(256));
        assert_eq!(vec![0,0,2,1], to_bytes(16908288), "{:?}, {:?}", vec![1,1,0,0], to_bytes(256));
        assert_eq!(vec![255,255,255,255], to_bytes(4294967295), "{:?}, {:?}", vec![1,1,0,0], to_bytes(256));
    }

}