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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//! An implementation of the [BLAKE hash function](http://131002.net/blake), via FFI to reference implementation.
//!
//! For more information about BLAKE visit its [official homepage](http://131002.net/blake).
//!
//! There are two APIs provided: one for single-chunk hashing and one for hashing of multiple data segments.
//!
//! # Examples
//!
//! Hashing a single chunk of data with a 256-bit BLAKE hash function, then verifying the result.
//!
//! ```
//! # use blake::Blake;
//! # use std::iter::FromIterator;
//! let mut result = [0; 32];
//! blake::hash(256, b"The lazy fox jumps over the lazy dog", &mut result).unwrap();
//!
//! assert_eq!(Vec::from_iter(result.iter().map(|&i| i)),
//!            vec![0x1B, 0x59, 0x7C, 0x7A, 0x88, 0x9F, 0xCE, 0xB1,
//!                 0xCC, 0x75, 0x6D, 0x6C, 0x6C, 0x06, 0xA7, 0xF9,
//!                 0x22, 0x5E, 0x02, 0xBB, 0x0C, 0x02, 0x6E, 0x8B,
//!                 0xC5, 0xEB, 0x4E, 0xA7, 0x61, 0x0E, 0xBB, 0x9E]);
//! ```
//!
//! Hashing multiple chunks of data with a 512-bit BLAKE hash function, then verifying the result.
//!
//! ```
//! # use blake::Blake;
//! # use std::iter::FromIterator;
//! let mut result = [0; 64];
//! let mut state = Blake::new(512).unwrap();
//!
//! state.update("Zażółć ".as_bytes());
//! state.update("gęślą ".as_bytes());
//! state.update("jaźń".as_bytes());
//!
//! state.finalise(&mut result);
//! assert_eq!(Vec::from_iter(result.iter().map(|&i| i)),
//!            vec![0x34, 0x43, 0xD3, 0x15, 0x00, 0x60, 0xFE, 0x8D,
//!                 0xBB, 0xB1, 0x21, 0x74, 0x87, 0x7B, 0x8A, 0xA2,
//!                 0x67, 0x19, 0xED, 0xC9, 0x66, 0xD6, 0xEC, 0xB5,
//!                 0x8F, 0x94, 0xBD, 0xE3, 0x5A, 0xD8, 0x96, 0x99,
//!                 0xEA, 0x03, 0xEB, 0xC2, 0x0E, 0x2B, 0xCD, 0x80,
//!                 0x5C, 0x0B, 0x09, 0x95, 0x6A, 0x1E, 0xEE, 0x3D,
//!                 0x1F, 0x07, 0x2B, 0x33, 0x64, 0x47, 0x15, 0x68,
//!                 0x10, 0x9E, 0x43, 0xC4, 0x0C, 0xE1, 0x27, 0xDA]);
//! ```
//!
//! Comparing result of single- and multi-chunk hash methods hashing the same effective message with a 384-bit BLAKE hash
//! function.
//!
//! ```
//! # use blake::Blake;
//! # use std::iter::FromIterator;
//! let mut result_multi  = [0; 48];
//! let mut result_single = [0; 48];
//!
//! let mut state = Blake::new(384).unwrap();
//! state.update("Zażółć ".as_bytes());
//! state.update("gęślą ".as_bytes());
//! state.update("jaźń".as_bytes());
//! state.finalise(&mut result_multi);
//!
//! blake::hash(384, "Zażółć gęślą jaźń".as_bytes(), &mut result_single).unwrap();
//!
//! assert_eq!(Vec::from_iter(result_multi .iter().map(|&i| i)),
//!            Vec::from_iter(result_single.iter().map(|&i| i)));
//! ```
//!
//! # Special thanks
//!
//! To all who support further development on [Patreon](https://patreon.com/nabijaczleweli), in particular:
//!
//!   * ThePhD
//!   * Embark Studios

extern crate libc;

mod native;

use std::error::Error;
use std::fmt;
use std::io;


/// Helper result type containing `BlakeError`.
pub type Result<T> = std::result::Result<T, BlakeError>;


/// Hash all data in one fell swoop.
///
/// Refer to individual functions for extended documentation.
///
/// # Example
///
/// ```
/// # use blake::Blake;
/// # use std::iter::FromIterator;
/// let mut result_256 = [0; 32];
/// let mut result_512 = [0; 64];
///
/// blake::hash(256, &[], &mut result_256).unwrap();
/// blake::hash(512, &[], &mut result_512).unwrap();
///
/// assert_eq!(Vec::from_iter(result_256.iter().map(|&i| i)),
///            vec![0x71, 0x6F, 0x6E, 0x86, 0x3F, 0x74, 0x4B, 0x9A,
///                 0xC2, 0x2C, 0x97, 0xEC, 0x7B, 0x76, 0xEA, 0x5F,
///                 0x59, 0x08, 0xBC, 0x5B, 0x2F, 0x67, 0xC6, 0x15,
///                 0x10, 0xBF, 0xC4, 0x75, 0x13, 0x84, 0xEA, 0x7A]);
/// assert_eq!(Vec::from_iter(result_512.iter().map(|&i| i)),
///            vec![0xA8, 0xCF, 0xBB, 0xD7, 0x37, 0x26, 0x06, 0x2D,
///                 0xF0, 0xC6, 0x86, 0x4D, 0xDA, 0x65, 0xDE, 0xFE,
///                 0x58, 0xEF, 0x0C, 0xC5, 0x2A, 0x56, 0x25, 0x09,
///                 0x0F, 0xA1, 0x76, 0x01, 0xE1, 0xEE, 0xCD, 0x1B,
///                 0x62, 0x8E, 0x94, 0xF3, 0x96, 0xAE, 0x40, 0x2A,
///                 0x00, 0xAC, 0xC9, 0xEA, 0xB7, 0x7B, 0x4D, 0x4C,
///                 0x2E, 0x85, 0x2A, 0xAA, 0xA2, 0x5A, 0x63, 0x6D,
///                 0x80, 0xAF, 0x3F, 0xC7, 0x91, 0x3E, 0xF5, 0xB8]);
/// ```
pub fn hash(hashbitlen: i32, data: &[u8], hashval: &mut [u8]) -> Result<()> {
    match unsafe { native::BLAKE_Hash_Hash(hashbitlen, data.as_ptr(), data.len() as u64 * 8, hashval.as_mut_ptr()) } {
        0 => Ok(()),
        e => Err(BlakeError::from(e)),
    }
}

/// Hashing state for multiple data sets.
///
/// # Example
///
/// Hashing a string split into multiple chunks.
///
/// ```
/// # use blake::Blake;
/// # use std::iter::FromIterator;
/// let mut state = Blake::new(256).unwrap();
///
/// state.update(b"Abolish ");
/// state.update(b"the ");
/// state.update(b"bourgeoisie");
/// state.update(b"!");
///
/// let mut result = [0; 32];
/// state.finalise(&mut result);
/// assert_eq!(Vec::from_iter(result.iter().map(|&i| i)),
///            vec![0x35, 0xBF, 0x9C, 0x70, 0xFF, 0x63, 0xF1, 0x26,
///                 0x6A, 0xE7, 0x2C, 0xC9, 0x94, 0x6F, 0x59, 0xBB,
///                 0x0B, 0x21, 0xD8, 0xCC, 0x8E, 0x4D, 0xBB, 0x53,
///                 0x24, 0xDF, 0x10, 0xB7, 0x11, 0xF9, 0x82, 0x1C]);
/// ```
///
/// A `Write` implementation is also provided:
///
/// ```
/// # use std::iter::FromIterator;
/// # use blake::Blake;
/// # use std::io;
/// let mut state = Blake::new(256).unwrap();
/// io::copy(&mut &b"The lazy fox jumps over the lazy dog."[..], &mut state).unwrap();
///
/// let mut result = [0; 32];
/// state.finalise(&mut result);
/// assert_eq!(Vec::from_iter(result.iter().map(|&i| i)),
///            vec![0xF2, 0xE5, 0xA9, 0xD0, 0x93, 0xD8, 0xAA, 0x23,
///                 0x4E, 0x6C, 0x54, 0x50, 0x61, 0xE8, 0x17, 0xBE,
///                 0x83, 0x8B, 0x57, 0xD8, 0x99, 0x8F, 0x15, 0xDF,
///                 0x72, 0xE1, 0x03, 0x7F, 0xBF, 0xEB, 0x4F, 0xC7]);
/// ```
pub struct Blake {
    raw_state: native::FFIHashState,
}

/// Some functions in the library can fail, this enum represents all the possible ways they can.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum BlakeError {
    /// Generic failure state
    Fail,
    /// `hashbitlen` passed to `Blake::new()` or `hash()` incorrect
    BadHashbitlen,
}


impl Blake {
    /// Create a new hash state and initialise it with the given bit length.
    ///
    /// `hashbitlen` is the hash output length. <br />
    /// Valid values:
    ///
    ///   * `224`,
    ///   * `256`,
    ///   * `384`,
    ///   * `512`.
    ///
    /// Returns:
    ///
    ///   * `Err(BlakeError::BadHashbitlen)` if `hashbitlen` is not any of the mentioned above, or
    ///   * `Ok(Blake)` if initialisation succeeds.
    ///
    /// # Examples
    ///
    /// Incorrect `hashbitlen`
    ///
    /// ```
    /// # use blake::Blake;
    /// assert_eq!(Blake::new(0).map(|_| ()), Err(blake::BlakeError::BadHashbitlen));
    /// ```
    ///
    /// Creating a 512-long state
    ///
    /// ```
    /// # use blake::Blake;
    /// Blake::new(512).unwrap();
    /// ```
    pub fn new(hashbitlen: i32) -> Result<Blake> {
        let mut raw_state = native::malloc_hash_state();

        match unsafe { native::BLAKE_Hash_Init(raw_state, hashbitlen) } {
            0 => Ok(Blake { raw_state: raw_state }),
            e => {
                native::free_hash_state(&mut raw_state);
                Err(BlakeError::from(e))
            }
        }
    }

    /// Add a salt to the hash function.
    ///
    /// Returns:
    ///
    ///   * `Err(BlakeError::Fail)` if called after `Blake::update()`, or
    ///   * `Ok(())`, if called before `Blake::update()`.
    ///
    /// The salt's length depends on the hash function's length.
    ///
    /// |hash function length|salt length|
    /// |--------------------|-----------|
    /// |      224 bits      |  128 bits |
    /// |      256 bits      |  128 bits |
    /// |      384 bits      |  256 bits |
    /// |      512 bits      |  256 bits |
    ///
    /// # Examples
    ///
    /// ```
    /// # use blake::Blake;
    /// # use std::iter::FromIterator;
    /// let mut result_unsalted = [0; 64];
    /// let mut result_salted   = [0; 64];
    ///
    /// let mut state_unsalted = Blake::new(512).unwrap();
    /// let mut state_salted   = Blake::new(512).unwrap();
    ///
    /// state_salted.add_salt(b"Violent  murder  of  the  proles").unwrap();
    ///
    /// state_unsalted.update(&[]);
    /// state_salted  .update(&[]);
    ///
    /// state_unsalted.finalise(&mut result_unsalted);
    /// state_salted  .finalise(&mut result_salted);
    ///
    /// assert!(Vec::from_iter(result_unsalted.iter().map(|&i| i)) !=
    ///         Vec::from_iter(result_salted  .iter().map(|&i| i)))
    /// ```
    pub fn add_salt(&mut self, salt: &[u8]) -> Result<()> {
        match unsafe { native::BLAKE_Hash_AddSalt(self.raw_state, salt.as_ptr()) } {
            0 => Ok(()),
            e => Err(BlakeError::from(e)),
        }
    }

    /// Append the provided data to the hash function.
    ///
    /// # Examples
    ///
    /// Hashing a part of [a short story](http://nabijaczleweli.xyz/capitalism/writing/Świat_to_kilka_takich_pokoi/)
    ///
    /// ```
    /// # use blake::Blake;
    /// # use std::iter::FromIterator;
    /// let mut result = [0; 64];
    ///
    /// let mut state = Blake::new(512).unwrap();
    /// state.update("    Serbiańcy znowu się pochlali, ale w sumie".as_bytes());
    /// state.update("czegoż się po wschodnich słowianach spodziewać, swoją".as_bytes());
    /// state.update("drogą. I, jak to wszystkim homo sapiensom się dzieje".as_bytes());
    /// state.update("filozofować poczęli.".as_bytes());
    /// state.finalise(&mut result);
    ///
    /// assert_eq!(Vec::from_iter(result.iter().map(|&i| i)),
    ///            vec![0xA2, 0x30, 0x50, 0x18, 0x10, 0x0D, 0x53, 0x61,
    ///                 0xC2, 0x2D, 0x61, 0x0A, 0x23, 0x4E, 0xA5, 0x28,
    ///                 0x18, 0x89, 0xA6, 0x44, 0x6E, 0xE1, 0xC4, 0x8A,
    ///                 0xDF, 0xD0, 0x6A, 0xDB, 0x1C, 0x00, 0x06, 0xA9,
    ///                 0x05, 0x0A, 0xCE, 0xB3, 0x43, 0x14, 0xB8, 0xB0,
    ///                 0x3F, 0xA3, 0xB7, 0x70, 0x5D, 0xFC, 0x14, 0xB9,
    ///                 0xAA, 0xCA, 0xDC, 0x5B, 0x34, 0x96, 0x0B, 0x3C,
    ///                 0x87, 0x1F, 0x69, 0x46, 0xCD, 0xC2, 0xB2, 0x14]);
    /// ```
    pub fn update(&mut self, data: &[u8]) {
        unsafe {
            native::BLAKE_Hash_Update(self.raw_state, data.as_ptr(), data.len() as u64 * 8);
        }
    }


    /// Finish hashing and store the output result in the provided space.
    ///
    /// The provided space must not be smaller than the hash function's size,
    /// if the provided space is smaller than the hash function's size, the behaviour is undefined.
    ///
    /// # Examples
    ///
    /// Storing and verifying results of all possible sizes.
    ///
    /// ```
    /// # use blake::Blake;
    /// # use std::iter::FromIterator;
    /// let mut result_224 = [0; 28];
    /// let mut result_256 = [0; 32];
    /// let mut result_384 = [0; 48];
    /// let mut result_512 = [0; 64];
    ///
    /// let mut state_224 = Blake::new(224).unwrap();
    /// let mut state_256 = Blake::new(256).unwrap();
    /// let mut state_384 = Blake::new(384).unwrap();
    /// let mut state_512 = Blake::new(512).unwrap();
    ///
    /// state_224.update(b"The lazy fox jumps over the lazy dog.");
    /// state_256.update(b"The lazy fox jumps over the lazy dog.");
    /// state_384.update(b"The lazy fox jumps over the lazy dog.");
    /// state_512.update(b"The lazy fox jumps over the lazy dog.");
    ///
    /// state_224.finalise(&mut result_224);
    /// state_256.finalise(&mut result_256);
    /// state_384.finalise(&mut result_384);
    /// state_512.finalise(&mut result_512);
    ///
    /// assert_eq!(Vec::from_iter(result_224.iter().map(|&i| i)),
    ///            vec![0x34, 0x97, 0x89, 0x0F, 0xBC, 0x6A, 0x98, 0x1C,
    ///                 0xD2, 0x21, 0x34, 0x97, 0xE4, 0xA8, 0x0A, 0x66,
    ///                 0xD6, 0x5F, 0x4C, 0x05, 0x3D, 0x71, 0x0F, 0x7E,
    ///                 0xAB, 0x81, 0xA4, 0x2F]);
    /// assert_eq!(Vec::from_iter(result_256.iter().map(|&i| i)),
    ///            vec![0xF2, 0xE5, 0xA9, 0xD0, 0x93, 0xD8, 0xAA, 0x23,
    ///                 0x4E, 0x6C, 0x54, 0x50, 0x61, 0xE8, 0x17, 0xBE,
    ///                 0x83, 0x8B, 0x57, 0xD8, 0x99, 0x8F, 0x15, 0xDF,
    ///                 0x72, 0xE1, 0x03, 0x7F, 0xBF, 0xEB, 0x4F, 0xC7]);
    /// assert_eq!(Vec::from_iter(result_384.iter().map(|&i| i)),
    ///            vec![0xDD, 0x68, 0x1E, 0x3B, 0x56, 0xE4, 0x80, 0x01,
    ///                 0x39, 0x5A, 0xF7, 0xB7, 0x36, 0x7E, 0x50, 0xD2,
    ///                 0x74, 0x61, 0x2B, 0xC8, 0xCB, 0xFB, 0x42, 0xEE,
    ///                 0x0C, 0xEC, 0x30, 0x45, 0x9C, 0x8D, 0x01, 0x66,
    ///                 0xFC, 0xB5, 0x42, 0xE2, 0x8C, 0xB0, 0x59, 0x72,
    ///                 0x8D, 0x7B, 0x0A, 0x16, 0x05, 0x4E, 0xB2, 0xEB]);
    /// assert_eq!(Vec::from_iter(result_512.iter().map(|&i| i)),
    ///            vec![0x9A, 0xD4, 0x66, 0xCF, 0x81, 0x8B, 0x46, 0x9D,
    ///                 0x29, 0x8C, 0x62, 0x00, 0xAC, 0xD3, 0x06, 0xF9,
    ///                 0xA2, 0xF4, 0xA4, 0x9E, 0x26, 0x8C, 0xA1, 0x17,
    ///                 0xB5, 0x8F, 0x37, 0x84, 0x86, 0x35, 0x1B, 0x0A,
    ///                 0x71, 0x1B, 0x60, 0xD4, 0x1B, 0x68, 0x7F, 0xD3,
    ///                 0x5F, 0x30, 0xBE, 0x2E, 0x00, 0xA8, 0x25, 0xD6,
    ///                 0x66, 0x6D, 0x9C, 0x4C, 0x23, 0xA5, 0x23, 0xD3,
    ///                 0x10, 0xA0, 0x58, 0x3F, 0x1E, 0x7C, 0xCC, 0xFE]);
    /// ```
    pub fn finalise(&mut self, hashval: &mut [u8]) {
        unsafe {
            native::BLAKE_Hash_Final(self.raw_state, hashval.as_mut_ptr());
        }
    }
}

/// The `Write` implementation updates the state with the provided data.
///
/// For example, to hash a file:
///
/// ```
/// # use std::iter::FromIterator;
/// # use std::fs::File;
/// # use blake::Blake;
/// # use std::io;
/// let mut state = Blake::new(256).unwrap();
/// io::copy(&mut File::open("LICENSE").unwrap(), &mut state).unwrap();
///
/// let mut result = [0; 32];
/// state.finalise(&mut result);
/// assert_eq!(Vec::from_iter(result.iter().map(|&i| i)),
///            vec![0xED, 0xE4, 0xD8, 0xF8, 0x49, 0x25, 0xD0, 0xBD,
///                 0x06, 0xA4, 0xDC, 0x1C, 0xFD, 0x1B, 0x45, 0x62,
///                 0xA4, 0xBD, 0x35, 0x25, 0x76, 0x9B, 0x97, 0xF1,
///                 0x9B, 0x21, 0xC8, 0xDF, 0xDC, 0x4A, 0x80, 0xB1]);
/// ```
impl io::Write for Blake {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.update(buf);
        Ok(buf.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

impl Drop for Blake {
    fn drop(&mut self) {
        native::free_hash_state(&mut self.raw_state);
    }
}


impl Error for BlakeError {
    fn description(&self) -> &str {
        match self {
            &BlakeError::Fail => "Generic BLAKE fail",
            &BlakeError::BadHashbitlen => "Incorrect hashbitlen",
        }
    }
}

impl From<i32> for BlakeError {
    /// Passing incorrect error values yields unspecified behaviour.
    fn from(i: i32) -> Self {
        match i {
            0 => panic!("Not an error"),
            1 => BlakeError::Fail,
            2 => BlakeError::BadHashbitlen,
            _ => panic!("Incorrect error number"),
        }
    }
}

impl fmt::Display for BlakeError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}