blake2b: Allow consuming partial BLAKE2b output

Some consumers were relying on the libsodium behaviour that the output
length was not checked against the configured hash output length.
blake2b_simd::Hash::as_bytes returns a correctly-sized slice, which we
were then failing to copy into the consumer's buffer. Instead of
requiring the consumer to provide a full-length buffer and then truncate
the output themselves (likely causing a double-copy, as we don't have
nice slices in C++), we instead allow the consumer to consume up to the
maximum output.
This commit is contained in:
Jack Grigg 2020-08-18 20:48:44 +01:00
parent 2d172e121f
commit 02b7d2afa2
2 changed files with 6 additions and 3 deletions

View File

@ -41,8 +41,8 @@ void blake2b_update(
/// Finalizes the `state` and stores the result in `output`. /// Finalizes the `state` and stores the result in `output`.
/// ///
/// `output_len` MUST be the same value as was passed as the first parameter to /// `output_len` MUST be less than or equal to the value that was passed as the
/// `blake2b_init`. /// first parameter to `blake2b_init`.
/// ///
/// This method is idempotent, and calling it multiple times will give the same /// This method is idempotent, and calling it multiple times will give the same
/// result. It's also possible to call `blake2b_update` with more input in /// result. It's also possible to call `blake2b_update` with more input in

View File

@ -49,5 +49,8 @@ pub extern "C" fn blake2b_finalize(state: *mut State, output: *mut c_uchar, outp
let state = unsafe { state.as_mut().unwrap() }; let state = unsafe { state.as_mut().unwrap() };
let output = unsafe { slice::from_raw_parts_mut(output, output_len) }; let output = unsafe { slice::from_raw_parts_mut(output, output_len) };
output.copy_from_slice(state.finalize().as_bytes()); // Allow consuming only part of the output.
let hash = state.finalize();
assert!(output_len <= hash.as_bytes().len());
output.copy_from_slice(&hash.as_bytes()[..output_len]);
} }