Skip to main content

Crate digest

Crate digest 

Source
Expand description

§RustCrypto: Digest Algorithm Traits

crate Docs Apache2/MIT licensed Rust Version Project Chat Build Status

Traits which describe functionality of cryptographic hash functions, a.k.a. digest algorithms.

See RustCrypto/hashes for implementations which use this trait.

§Usage

Let us demonstrate how to use crates in this repository using Sha256 as an example.

First add the sha2 crate to your Cargo.toml:

[dependencies]
sha2 = "0.11"

sha2 and other crates re-export digest crate and Digest trait for convenience, so you don’t have to add digest crate as an explicit dependency.

Now you can write the following code:

use sha2::{Sha256, Digest};

let mut hasher = Sha256::new();
let data = b"Hello world!";
hasher.update(data);
// `input` can be called repeatedly and is generic over `AsRef<[u8]>`
hasher.update("String data");
// Note that calling `finalize()` consumes hasher
let hash = hasher.finalize();
println!("Result: {:?}", hash);

In this example hash has type Array<u8, U32>, which is a generic alternative to [u8; 32].

Alternatively you can use chained approach, which is equivalent to the previous example:

use sha2::{Sha256, Digest};

let hash = Sha256::new()
    .chain_update(b"Hello world!")
    .chain_update("String data")
    .finalize();

println!("Result: {:?}", hash);

If the whole message is available you also can use convenience digest method:

use sha2::{Sha256, Digest};

let hash = Sha256::digest(b"my message");
println!("Result: {:?}", hash);

§Generic code

You can write generic code over Digest (or other traits from digest crate) trait which will work over different hash functions:

use digest::Digest;

// Toy example, do not use it in practice!
// Instead use crates from: https://github.com/RustCrypto/password-hashing
fn hash_password<D: Digest>(password: &str, salt: &str, output: &mut [u8]) {
    let mut hasher = D::new();
    hasher.update(password.as_bytes());
    hasher.update(b"$");
    hasher.update(salt.as_bytes());
    output.copy_from_slice(hasher.finalize().as_slice())
}

let mut buf1 = [0u8; 32];
let mut buf2 = [0u8; 64];

hash_password::<sha2::Sha256>("my_password", "abcd", &mut buf1);
hash_password::<sha2::Sha512>("my_password", "abcd", &mut buf2);

If you want to use hash functions with trait objects, use digest::DynDigest trait.

§License

Licensed under either of:

at your option.

§Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

§Structure

Traits in this crate are organized into the following levels:

  • High-level convenience traits: Digest, DynDigest, Mac. Wrappers around lower-level traits for most common use-cases. Users should usually prefer using these traits.
  • Mid-level traits: Update, FixedOutput, FixedOutputReset, ExtendableOutput, ExtendableOutputReset, XofReader, Reset, KeyInit, and InnerInit. These traits atomically describe available functionality of an algorithm.
  • Marker traits: HashMarker, MacMarker. Used to distinguish different algorithm classes.
  • Low-level traits defined in the block_api module. These traits operate at a block-level and do not contain any built-in buffering. They are intended to be implemented by low-level algorithm providers only. Usually they should not be used in application-level code.

Additionally hash functions implement traits from the standard library: Default and Clone.

This crate does not provide any implementations of the io::Read/Write traits, see the digest-io crate for std::io-compatibility wrappers.

Re-exports§

pub use common::rand_core;rand_core
pub use zeroize;zeroize
pub use block_buffer;block-api
pub use common;
pub use const_oid;oid
pub use common::array;
pub use common::typenum;

Modules§

block_apiblock-api
Low-level traits operating on blocks and wrappers around them.
consts
devdev
Development-related functionality

Macros§

bench_update
Define Update impl benchmark
buffer_ct_variable
Creates a buffered wrapper around block-level “core” type which implements variable output size traits with output size selected at compile time.
buffer_fixed
Creates a buffered wrapper around block-level “core” type which implements fixed output size traits.
buffer_xof
Creates a buffered wrapper around block-level “core” type which implements extendable output size traits.
hash_rt_outsize_serialization_test
Define hash function serialization test
hash_serialization_test
Define hash function serialization test
new_mac_test
Define MAC test
new_test
Define hash function test

Structs§

CtOutputmac
Fixed size output value which provides a safe Eq implementation that runs in constant time.
InvalidBufferSize
Buffer length is not equal to hash output size.
InvalidLengthmac
The error type returned when key and/or IV used in the KeyInit, KeyIvInit, and InnerIvInit slice-based methods had an invalid length.
InvalidOutputSize
The error type used in variable hash traits.
MacErrormac
Error type for when the Output of a Mac is not equal to the expected value.
XofFixedWrapper
Wrapper around ExtendableOutput types adding OutputSizeUser with the given size of S.

Traits§

CollisionResistance
Types with a certain collision resistance.
CustomizedInit
Trait for hash functions with customization string for domain separation.
Digest
Convenience wrapper trait covering functionality of cryptographic hash functions with fixed output size.
DynDigest
Modification of the Digest trait suitable for trait objects.
DynDigestWithOidoid
Convenience wrapper trait around DynDigest and DynAssociatedOid.
ExtendableOutput
Trait for hash functions with extendable-output (XOF).
ExtendableOutputReset
Trait for hash functions with extendable-output (XOF) able to reset themselves.
FixedOutput
Trait for hash functions with fixed-size output.
FixedOutputReset
Trait for hash functions with fixed-size output able to reset themselves.
HashMarker
Marker trait for cryptographic hash functions.
InnerInitmac
Types which can be initialized from another type (usually block ciphers).
KeyInitmac
Types which can be initialized from a key.
Macmac
Convenience wrapper trait covering functionality of Message Authentication algorithms.
MacMarkermac
Marker trait for Message Authentication algorithms.
OutputSizeUser
Types which return data with the given size.
Reset
Resettable types.
Update
Types which consume data with byte granularity.
XofReader
Trait for reader types which are used to extract extendable output from a XOF (extendable-output function) result.

Type Aliases§

Keymac
Key used by KeySizeUser implementors.
Output
Output array of OutputSizeUser implementors.