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
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
use crate::blake2b_ref::{
    blake2b_final, blake2b_init_key_with_param, blake2b_init_param, blake2b_param, blake2b_state,
    blake2b_update, size_t, BLAKE2B_KEYBYTES, BLAKE2B_OUTBYTES, BLAKE2B_PERSONALBYTES,
    BLAKE2B_SALTBYTES,
};
use crate::libc::*;

pub struct Blake2b {
    pub(crate) state: blake2b_state,
}

pub struct Blake2bBuilder {
    pub(crate) state: blake2b_state,
    pub(crate) param: blake2b_param,
    pub(crate) key_len: usize,
    pub(crate) key: [u8; BLAKE2B_KEYBYTES as usize],
}

impl Blake2bBuilder {
    pub fn new(out_len: usize) -> Self {
        assert!(out_len >= 1 && out_len <= BLAKE2B_OUTBYTES as usize);
        let param = blake2b_param {
            digest_length: out_len as u8,
            key_length: 0,
            fanout: 1,
            depth: 1,
            leaf_length: 0,
            node_offset: 0,
            xof_length: 0,
            node_depth: 0,
            inner_length: 0,
            reserved: [0u8; 14usize],
            salt: [0u8; BLAKE2B_SALTBYTES as usize],
            personal: [0u8; BLAKE2B_PERSONALBYTES as usize],
        };
        let state = unsafe { ::core::mem::MaybeUninit::zeroed().assume_init() }; // initialize when build called
        let key_len = 0;
        let key = [0u8; BLAKE2B_KEYBYTES as usize];

        Blake2bBuilder {
            param,
            state,
            key_len,
            key,
        }
    }

    pub fn salt(mut self, salt: &[u8]) -> Blake2bBuilder {
        let len = salt.len();
        assert!(len <= BLAKE2B_SALTBYTES as usize);

        unsafe {
            ::core::ptr::copy_nonoverlapping(salt.as_ptr(), self.param.salt.as_mut_ptr(), len);
        }
        self
    }

    pub fn personal(mut self, personal: &[u8]) -> Blake2bBuilder {
        let len = personal.len();
        assert!(len <= BLAKE2B_PERSONALBYTES as usize);

        unsafe {
            ::core::ptr::copy_nonoverlapping(
                personal.as_ptr(),
                self.param.personal.as_mut_ptr(),
                len,
            );
        }
        self
    }

    pub fn key(mut self, key: &[u8]) -> Blake2bBuilder {
        let key_len = key.len();
        assert!(key_len <= BLAKE2B_KEYBYTES as usize);
        self.param.key_length = key_len as u8;
        self.key_len = key_len;

        unsafe {
            ::core::ptr::copy_nonoverlapping(key.as_ptr(), self.key.as_mut_ptr(), key_len);
        }
        self
    }

    pub fn build(self) -> Blake2b {
        let Blake2bBuilder {
            mut state,
            param,
            key,
            key_len,
        } = self;
        if self.key_len == 0 {
            unsafe {
                blake2b_init_param(
                    &mut state as *mut blake2b_state,
                    &param as *const blake2b_param,
                );
            }
        } else {
            unsafe {
                blake2b_init_key_with_param(
                    &mut state as *mut blake2b_state,
                    &param as *const blake2b_param,
                    key.as_ptr() as *const c_void,
                    key_len as size_t,
                );
            }
        }
        Blake2b { state }
    }
}

impl Blake2b {
    pub fn update(&mut self, data: &[u8]) {
        unsafe {
            blake2b_update(
                &mut self.state as *mut blake2b_state,
                data.as_ptr() as *const c_void,
                data.len() as size_t,
            );
        }
    }

    pub fn finalize(mut self, dst: &mut [u8]) {
        unsafe {
            blake2b_final(
                &mut self.state as *mut blake2b_state,
                dst.as_mut_ptr() as *mut c_void,
                dst.len() as size_t,
            );
        }
    }
}

pub fn blake2b(key: &[u8], data: &[u8], dst: &mut [u8]) {
    let mut blake2b = Blake2bBuilder::new(dst.len()).key(key).build();
    blake2b.update(data);
    blake2b.finalize(dst)
}

#[cfg(test)]
mod tests {
    use super::Blake2bBuilder;
    use faster_hex::{hex_decode, hex_string};
    use serde_derive::Deserialize;
    use std::fs::File;
    use std::io::BufReader;
    use std::path::Path;

    #[derive(Deserialize, Debug)]
    struct TestItem {
        outlen: usize,
        out: String,
        input: String,
        key: String,
        salt: String,
        personal: String,
    }

    #[test]
    fn test_full() {
        let test_path = Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/test.json");

        let f = File::open(test_path).unwrap();
        let reader = BufReader::new(f);
        let tests: Vec<TestItem> = serde_json::from_reader(reader).unwrap();

        for test in tests {
            let mut hash = vec![0u8; test.outlen];
            let mut blake2b = Blake2bBuilder::new(test.outlen)
                .key(&unhex(test.key.as_bytes()))
                .personal(&unhex(test.personal.as_bytes()))
                .salt(&unhex(test.salt.as_bytes()))
                .build();
            blake2b.update(&unhex(test.input.as_bytes()));
            blake2b.finalize(&mut hash);
            assert_eq!(hex_string(&hash).unwrap(), test.out);
        }
    }

    fn unhex(src: &[u8]) -> Vec<u8> {
        let len = src.len() / 2;
        let mut ret = vec![0u8; len];
        if !src.is_empty() {
            hex_decode(src, &mut ret).unwrap();
        }
        ret
    }
}