#hash #write #data #sha-256 #hashing #hasher #sha-2

write-hasher

Transparently calculate hash on (asynchronously) writing to an type

1 unstable release

0.1.2 May 24, 2023
0.1.1 Apr 27, 2023
0.1.0 Apr 27, 2023

#2584 in Cryptography

40 downloads per month

MIT license

18KB
364 lines

WriteHasher

Hash the data being written to a writer.
Supports tokio::io::AsyncWrite, futures::io::AsyncWrite, std::io::Write.

Example

extern crate sha2;
use sha2::Sha256;
use write_hasher::WriteHasher;

let mut file = std::fs::File::open("Cargo.toml").unwrap();
let dest = std::io::sink();
let dest = WriteHasher::<Sha256, _>::new(dest);
std::io::copy(&mut file, &mut dest).unwrap();
let hash = dest.finalize();

You can use async functions as well as std functions for this as well.


lib.rs:

A hasher that will be a wrapper over any
std::io::Write /
futures::io::AsyncWrite /
tokio::io::AsyncWrite object

You can wrap any of the previous trait object inside and that will transparently hash the data that is being written to it.

The object should implement AsyncRead so that it can wrap some data and then read from that transparently while offloading the hashing to another thread.

extern crate sha2;
use write_hasher::{WriteHasher, MinDigest};
let mut src = std::fs::File::open(".gitignore").unwrap();
let sink = std::io::sink();
let mut hasher = WriteHasher::<sha2::Sha256, _>::new(sink);
std::io::copy(&mut src, &mut hasher).unwrap();
let x = hasher.finalize();
let x = format!("{:x}", x);
assert_eq!(
    "c1e953ee360e77de57f7b02f1b7880bd6a3dc22d1a69e953c2ac2c52cc52d247",
    x
);

Dependencies

~0.3–6MB
~34K SLoC