Skip to content

Commit

Permalink
Use hasher wrappers
Browse files Browse the repository at this point in the history
  • Loading branch information
AaronFeickert committed Aug 10, 2023
1 parent 03759b0 commit ddc40c7
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 50 deletions.
69 changes: 30 additions & 39 deletions src/hashing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -222,12 +222,11 @@ impl<D: Digest> AsRef<[u8]> for DomainSeparatedHash<D> {
/// Calculating a signature challenge
///
/// ```
/// # use blake2::Digest;
/// # use tari_utilities::hex::{to_hex, Hex};
/// use blake2::{Blake2b, Digest};
/// use digest::consts::U32;
/// use tari_crypto::{
/// # use tari_crypto::{
/// hash_domain,
/// hashing::{DomainSeparatedHash, DomainSeparatedHasher, DomainSeparation},
/// hashing::{Blake2b256, DomainSeparatedHash, DomainSeparatedHasher, DomainSeparation},
/// };
///
/// hash_domain!(CardHashDomain, "com.cards");
Expand All @@ -237,8 +236,8 @@ impl<D: Digest> AsRef<[u8]> for DomainSeparatedHash<D> {
/// strength: u8,
/// }
///
/// fn calculate_challenge(msg: &str) -> DomainSeparatedHash<Blake2b<U32>> {
/// DomainSeparatedHasher::<Blake2b<U32>, CardHashDomain>::new_with_label("schnorr_challenge")
/// fn calculate_challenge(msg: &str) -> DomainSeparatedHash<Blake2b256> {
/// DomainSeparatedHasher::<Blake2b256, CardHashDomain>::new_with_label("schnorr_challenge")
/// .chain_update(msg.as_bytes())
/// .finalize()
/// }
Expand Down Expand Up @@ -539,18 +538,13 @@ impl<D: Digest> Deref for Mac<D> {
/// # use tari_crypto::keys::SecretKey;
/// # use tari_crypto::ristretto::ristretto_keys::RistrettoKdf;
/// # use tari_crypto::ristretto::RistrettoSecretKey;
/// # use digest::consts::U64;
/// # use blake2::Blake2b;
/// # use tari_crypto::hashing::Blake2b512;
///
/// fn wallet_keys(
/// primary_key: &RistrettoSecretKey,
/// index: usize,
/// ) -> Result<RistrettoSecretKey, HashingError> {
/// RistrettoKdf::generate::<Blake2b<U64>>(
/// primary_key.as_bytes(),
/// &index.to_le_bytes(),
/// "wallet",
/// )
/// RistrettoKdf::generate::<Blake2b512>(primary_key.as_bytes(), &index.to_le_bytes(), "wallet")
/// }
///
/// let key = RistrettoSecretKey::from_hex(
Expand Down Expand Up @@ -655,17 +649,14 @@ pub fn create_hasher<D: Digest, HD: DomainSeparation>() -> DomainSeparatedHasher
#[cfg(test)]
mod test {
use blake2::Blake2b;
use digest::{
consts::{U32, U64},
generic_array::GenericArray,
Digest,
Update,
};
use digest::{consts::U32, generic_array::GenericArray, Digest, Update};
use tari_utilities::hex::{from_hex, to_hex};

use crate::hashing::{
byte_to_decimal_ascii_bytes,
AsFixedBytes,
Blake2b256,
Blake2b512,
DomainSeparatedHasher,
DomainSeparation,
Mac,
Expand Down Expand Up @@ -693,7 +684,7 @@ mod test {
#[test]
fn hasher_macro_tests() {
{
hasher!(Blake2b<U32>, MyDemoHasher, "com.macro.test");
hasher!(Blake2b256, MyDemoHasher, "com.macro.test");

util::hash_from_digest(
MyDemoHasher::new(),
Expand All @@ -702,7 +693,7 @@ mod test {
);
}
{
hasher!(Blake2b<U32>, MyDemoHasher2, "com.macro.test", 1);
hasher!(Blake2b256, MyDemoHasher2, "com.macro.test", 1);

util::hash_from_digest(
MyDemoHasher2::new(),
Expand All @@ -724,7 +715,7 @@ mod test {
#[test]
fn finalize_into() {
hash_domain!(TestHasher, "com.example.test");
let mut hasher = DomainSeparatedHasher::<Blake2b<U32>, TestHasher>::new();
let mut hasher = DomainSeparatedHasher::<Blake2b256, TestHasher>::new();
hasher.update([0, 0, 0]);

let mut output = GenericArray::<u8, U32>::default();
Expand All @@ -734,7 +725,7 @@ mod test {
#[test]
fn finalize_into_reset() {
hash_domain!(TestHasher, "com.example.test");
let mut hasher = DomainSeparatedHasher::<Blake2b<U32>, TestHasher>::new();
let mut hasher = DomainSeparatedHasher::<Blake2b256, TestHasher>::new();
hasher.update([0, 0, 0]);

let mut output = GenericArray::<u8, U32>::default();
Expand All @@ -747,7 +738,7 @@ mod test {
use zeroize::Zeroize;

hash_domain!(TestHasher, "com.example.test");
let mut hasher = DomainSeparatedHasher::<Blake2b<U32>, TestHasher>::new();
let mut hasher = DomainSeparatedHasher::<Blake2b256, TestHasher>::new();
hasher.update([0, 0, 0]);

hidden_type!(Key, SafeArray<u8, 32>);
Expand All @@ -759,10 +750,10 @@ mod test {
fn dst_hasher() {
hash_domain!(GenericHashDomain, "com.tari.generic");
assert_eq!(GenericHashDomain::domain_separation_tag(""), "com.tari.generic.v1");
let hash = DomainSeparatedHasher::<Blake2b<U32>, GenericHashDomain>::new_with_label("test_hasher")
let hash = DomainSeparatedHasher::<Blake2b256, GenericHashDomain>::new_with_label("test_hasher")
.chain("some foo")
.finalize();
let mut hash2 = DomainSeparatedHasher::<Blake2b<U32>, GenericHashDomain>::new_with_label("test_hasher");
let mut hash2 = DomainSeparatedHasher::<Blake2b256, GenericHashDomain>::new_with_label("test_hasher");
hash2.update("some foo");
let hash2 = hash2.finalize();
assert_eq!(hash.as_ref(), hash2.as_ref());
Expand All @@ -772,8 +763,8 @@ mod test {
);

let hash_1 =
DomainSeparatedHasher::<Blake2b<U32>, GenericHashDomain>::new_with_label("mynewtest").digest(b"rincewind");
let hash_2 = DomainSeparatedHasher::<Blake2b<U32>, GenericHashDomain>::new_with_label("mynewtest")
DomainSeparatedHasher::<Blake2b256, GenericHashDomain>::new_with_label("mynewtest").digest(b"rincewind");
let hash_2 = DomainSeparatedHasher::<Blake2b256, GenericHashDomain>::new_with_label("mynewtest")
.chain(b"rincewind")
.finalize();
assert_eq!(hash_1.as_ref(), hash_2.as_ref());
Expand All @@ -783,20 +774,20 @@ mod test {
fn digest_is_the_same_as_standard_api() {
hash_domain!(MyDemoHasher, "com.macro.test");
assert_eq!(MyDemoHasher::domain_separation_tag(""), "com.macro.test.v1");
util::hash_test::<DomainSeparatedHasher<Blake2b<U32>, MyDemoHasher>>(
util::hash_test::<DomainSeparatedHasher<Blake2b256, MyDemoHasher>>(
&[0, 0, 0],
"d4cbf5b6b97485a991973db8a6ce4d3fc660db5dff5f55f2b0cb363fca34b0a2",
);

let mut hasher = DomainSeparatedHasher::<Blake2b<U32>, MyDemoHasher>::new();
let mut hasher = DomainSeparatedHasher::<Blake2b256, MyDemoHasher>::new();
hasher.update([0, 0, 0]);
let hash = hasher.finalize();
assert_eq!(
to_hex(hash.as_ref()),
"d4cbf5b6b97485a991973db8a6ce4d3fc660db5dff5f55f2b0cb363fca34b0a2"
);

let mut hasher = DomainSeparatedHasher::<Blake2b<U32>, MyDemoHasher>::new_with_label("");
let mut hasher = DomainSeparatedHasher::<Blake2b256, MyDemoHasher>::new_with_label("");
hasher.update([0, 0, 0]);
let hash = hasher.finalize();
assert_eq!(
Expand All @@ -810,21 +801,21 @@ mod test {
fn can_be_used_as_digest() {
hash_domain!(MyDemoHasher, "com.macro.test");
assert_eq!(MyDemoHasher::domain_separation_tag(""), "com.macro.test.v1");
util::hash_test::<DomainSeparatedHasher<Blake2b<U32>, MyDemoHasher>>(
util::hash_test::<DomainSeparatedHasher<Blake2b256, MyDemoHasher>>(
&[0, 0, 0],
"d4cbf5b6b97485a991973db8a6ce4d3fc660db5dff5f55f2b0cb363fca34b0a2",
);

hash_domain!(MyDemoHasher2, "com.macro.test", 2);
assert_eq!(MyDemoHasher2::domain_separation_tag(""), "com.macro.test.v2");
util::hash_test::<DomainSeparatedHasher<Blake2b<U32>, MyDemoHasher2>>(
util::hash_test::<DomainSeparatedHasher<Blake2b256, MyDemoHasher2>>(
&[0, 0, 0],
"ce327b02271d035bad4dcc1e69bc292392ee4ee497f1f8467d54bf4b4c72639a",
);

hash_domain!(TariHasher, "com.tari.hasher");
assert_eq!(TariHasher::domain_separation_tag(""), "com.tari.hasher.v1");
util::hash_test::<DomainSeparatedHasher<Blake2b<U32>, TariHasher>>(
util::hash_test::<DomainSeparatedHasher<Blake2b256, TariHasher>>(
&[0, 0, 0],
"ae359f05bb76c646c6767d25f53893fc38b0c7b56f8a74a1cbb008ea3ffc183f",
);
Expand All @@ -834,7 +825,7 @@ mod test {
#[test]
fn hash_to_fixed_bytes_conversion() {
hash_domain!(TestDomain, "com.tari.generic");
let hash = DomainSeparatedHasher::<Blake2b<U32>, TestDomain>::new_with_label("mytest")
let hash = DomainSeparatedHasher::<Blake2b256, TestDomain>::new_with_label("mytest")
.chain("some data")
.finalize();
let hash_to_bytes_7: [u8; 7] = hash.as_fixed_bytes().unwrap();
Expand All @@ -849,7 +840,7 @@ mod test {
fn deconstruction() {
hash_domain!(TestDomain, "com.tari.generic");
// Illustrate exactly what gets hashed and how we try and avoid collisions
let hash = DomainSeparatedHasher::<Blake2b<U32>, TestDomain>::new_with_label("mytest")
let hash = DomainSeparatedHasher::<Blake2b256, TestDomain>::new_with_label("mytest")
.chain("rincewind")
.chain("hex")
.finalize();
Expand Down Expand Up @@ -879,7 +870,7 @@ mod test {
}
let domain = "com.discworld.v42.turtles";
assert_eq!(MyDemoHasher::domain_separation_tag("turtles"), domain);
let hash = DomainSeparatedHasher::<Blake2b<U32>, MyDemoHasher>::new_with_label("turtles").finalize();
let hash = DomainSeparatedHasher::<Blake2b256, MyDemoHasher>::new_with_label("turtles").finalize();
let expected = Blake2b::<U32>::default()
.chain((domain.len() as u64).to_le_bytes())
.chain(domain)
Expand Down Expand Up @@ -914,7 +905,7 @@ mod test {
"com.discworld"
}
}
let hash = DomainSeparatedHasher::<Blake2b<U64>, MyDemoHasher>::new_with_label("turtles")
let hash = DomainSeparatedHasher::<Blake2b512, MyDemoHasher>::new_with_label("turtles")
.chain("elephants")
.finalize();
assert_eq!(to_hex(hash.as_ref()), "64a89c7160a1076a725fac97d3f67803abd0991d82518a595072fa62df4c870bddee9160f591231c381087831bf6925616013de317ce0b02846585caf41942ac");
Expand All @@ -927,7 +918,7 @@ mod test {
// let mac = Mac::generate::<Sha256, _, _>(&key, "test message", "test");
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `LengthExtensionAttackResistant` is not implemented for
// `Sha256`
let mac = Mac::<Blake2b<U32>>::generate(key, "test message", "test");
let mac = Mac::<Blake2b256>::generate(key, "test message", "test");
assert_eq!(MacDomain::domain_separation_tag("test"), "com.tari.mac.v1.test");
assert_eq!(
to_hex(mac.as_ref()),
Expand Down
18 changes: 11 additions & 7 deletions src/ristretto/ristretto_keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};

use crate::{
errors::HashingError,
hashing::{DerivedKeyDomain, DomainSeparatedHasher, DomainSeparation},
hashing::{Blake2b512, DerivedKeyDomain, DomainSeparatedHasher, DomainSeparation},
keys::{PublicKey, SecretKey},
};

Expand Down Expand Up @@ -317,7 +317,7 @@ impl RistrettoPublicKey {
/// A verifiable group generator using a domain separated hasher
pub fn new_generator(label: &'static str) -> Result<RistrettoPublicKey, HashingError> {
// This function requires 512 bytes of data, so let's be opinionated here and use blake2b
let hash = DomainSeparatedHasher::<Blake2b<U64>, RistrettoGeneratorPoint>::new_with_label(label).finalize();
let hash = DomainSeparatedHasher::<Blake2b512, RistrettoGeneratorPoint>::new_with_label(label).finalize();
if hash.as_ref().len() < 64 {
return Err(HashingError::DigestTooShort { bytes: 64 });
}
Expand Down Expand Up @@ -622,7 +622,11 @@ mod test {
use tari_utilities::ByteArray;

use super::*;
use crate::{keys::PublicKey, ristretto::test_common::get_keypair};
use crate::{
hashing::{Blake2b256, Blake2b512},
keys::PublicKey,
ristretto::test_common::get_keypair,
};

fn assert_completely_equal(k1: &RistrettoPublicKey, k2: &RistrettoPublicKey) {
assert_eq!(k1, k2);
Expand Down Expand Up @@ -988,19 +992,19 @@ mod test {

#[test]
fn kdf_too_short() {
let err = RistrettoKdf::generate::<Blake2b<U32>>(b"this_hasher_is_too_short", b"data", "test").err();
let err = RistrettoKdf::generate::<Blake2b256>(b"this_hasher_is_too_short", b"data", "test").err();
assert!(matches!(err, Some(HashingError::InputTooShort {})));

let err = RistrettoKdf::generate::<Blake2b<U64>>(b"this_key_is_too_short", b"data", "test").err();
let err = RistrettoKdf::generate::<Blake2b512>(b"this_key_is_too_short", b"data", "test").err();
assert!(matches!(err, Some(HashingError::InputTooShort {})));
}

#[test]
fn kdf_test() {
let key =
RistrettoSecretKey::from_hex("45c5b950e04167785ff735bead8d746740db04bce3ee2c1f6523bdc59023e50e").unwrap();
let derived1 = RistrettoKdf::generate::<Blake2b<U64>>(key.as_bytes(), b"derived1", "test").unwrap();
let derived2 = RistrettoKdf::generate::<Blake2b<U64>>(key.as_bytes(), b"derived2", "test").unwrap();
let derived1 = RistrettoKdf::generate::<Blake2b512>(key.as_bytes(), b"derived1", "test").unwrap();
let derived2 = RistrettoKdf::generate::<Blake2b512>(key.as_bytes(), b"derived2", "test").unwrap();
assert_eq!(
derived1.to_hex(),
"22deb0c38ec2dc9f741912f6e3c2cd3f76a5b33142a289da15eecdcd882bda06"
Expand Down
3 changes: 2 additions & 1 deletion src/ristretto/ristretto_sig.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ mod test {

use crate::{
hash_domain,
hashing::Blake2b512,
keys::{PublicKey, SecretKey},
ristretto::{
ristretto_sig::RistrettoSchnorrWithDomain,
Expand Down Expand Up @@ -213,7 +214,7 @@ mod test {
let R =
RistrettoPublicKey::from_hex("fa14cb581ce5717248444721242e6b195a482d503a853dea4acb513074d8d803").unwrap();
let msg = "Moving Pictures";
let hash = SchnorrSignature::<_, _, SchnorrSigChallenge>::construct_domain_separated_challenge::<_, Blake2b<U64>>(
let hash = SchnorrSignature::<_, _, SchnorrSigChallenge>::construct_domain_separated_challenge::<_, Blake2b512>(
&R, &P, msg,
);
let naiive = Blake2b::<U64>::new()
Expand Down
6 changes: 3 additions & 3 deletions src/signatures/schnorr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use tari_utilities::ByteArray;

use crate::{
hash_domain,
hashing::{DomainSeparatedHash, DomainSeparatedHasher, DomainSeparation},
hashing::{Blake2b512, DomainSeparatedHash, DomainSeparatedHasher, DomainSeparation},
keys::{PublicKey, SecretKey},
};

Expand Down Expand Up @@ -158,7 +158,7 @@ where
let public_nonce = P::from_secret_key(&nonce);
let public_key = P::from_secret_key(secret);
let challenge =
Self::construct_domain_separated_challenge::<_, Blake2b<U64>>(&public_nonce, &public_key, message);
Self::construct_domain_separated_challenge::<_, Blake2b512>(&public_nonce, &public_key, message);
Self::sign_raw(secret, nonce, challenge.as_ref())
}

Expand Down Expand Up @@ -196,7 +196,7 @@ where
B: AsRef<[u8]>,
{
let challenge =
Self::construct_domain_separated_challenge::<_, Blake2b<U64>>(&self.public_nonce, public_key, message);
Self::construct_domain_separated_challenge::<_, Blake2b512>(&self.public_nonce, public_key, message);
self.verify_challenge(public_key, challenge.as_ref())
}

Expand Down

0 comments on commit ddc40c7

Please sign in to comment.