Skip to content

Commit

Permalink
Use Blake3's extendable output function (#216)
Browse files Browse the repository at this point in the history
* Use blake3's XOF function for output sizes other than 32 fixes #213

* minor fixes
- use expected result & rename new blake3 test
- use easier to read code for filling inner digest with blake3
  • Loading branch information
mriise authored May 19, 2022
1 parent f1d20e9 commit 3a3dacf
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 5 deletions.
16 changes: 11 additions & 5 deletions src/hasher_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,14 @@ pub mod blake3 {
digest: [u8; S],
}

impl<const S: usize> Blake3Hasher<S> {
/// using blake3's XOF function, fills the given slice with hash output
pub fn finalize_xof_fill(&mut self, digest_out: &mut [u8]) {
let mut digest = self.hasher.finalize_xof();
digest.fill(digest_out)
}
}

impl<const S: usize> Default for Blake3Hasher<S> {
fn default() -> Self {
let hasher = ::blake3::Hasher::new();
Expand All @@ -119,11 +127,9 @@ pub mod blake3 {
}

fn finalize(&mut self) -> &[u8] {
let digest = self.hasher.finalize(); //default is 32 bytes anyway
let digest_bytes = digest.as_bytes();
let digest_out = &mut self.digest[..digest_bytes.len().max(S)];
digest_out.copy_from_slice(digest_bytes);
digest_out
let mut output = self.hasher.finalize_xof();
output.fill(&mut self.digest);
&self.digest
}

fn reset(&mut self) {
Expand Down
40 changes: 40 additions & 0 deletions tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -335,3 +335,43 @@ fn multihash_errors() {
"Should error on wrong hash length"
);
}

#[test]
fn blak3_non_default_digest() {
use multihash::Blake3Hasher;
const DIGEST_SIZE: usize = 16;
pub struct ContentHasher(Blake3Hasher<DIGEST_SIZE>);

pub struct ContentHash([u8; DIGEST_SIZE]);

impl ContentHasher {
fn new() -> ContentHasher {
ContentHasher(Blake3Hasher::default())
}

fn write(&mut self, input: &[u8]) {
self.0.update(input);
}

fn finish(&mut self) -> ContentHash {
let hash = multihash::Code::Blake3_256.wrap(self.0.finalize()).unwrap();
let resized_hash = hash.resize::<DIGEST_SIZE>().unwrap();

let mut content = ContentHash([0u8; DIGEST_SIZE]);
content.0.copy_from_slice(resized_hash.digest());
content
}

fn reset(&mut self) {
self.0.reset();
}
}

let mut hasher = ContentHasher::new();
hasher.write("foobar".as_bytes());
let content_hash = hasher.finish();
hasher.reset();

let expected = hex::decode("aa51dcd43d5c6c5203ee16906fd6b35d").unwrap();
assert_eq!(&content_hash.0, expected.as_slice())
}

0 comments on commit 3a3dacf

Please sign in to comment.