Skip to content

Commit

Permalink
Truncate secret hash
Browse files Browse the repository at this point in the history
The `hex-conservative` crate does not truncate hashes when printed with
the `fmt` precision format parameter, this is as expected since a hash
is a 32 byte integer (I think) and for integral types precision is
ignorded.

Add a private struct to handle truncating, and truncate the hash to an 8
byte identifier.
  • Loading branch information
tcharding committed Aug 22, 2024
1 parent 789f384 commit a694b2c
Showing 1 changed file with 25 additions and 1 deletion.
26 changes: 25 additions & 1 deletion src/secret.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,31 @@ macro_rules! impl_display_secret {
engine.input(&self.secret_bytes());
let hash = sha256::Hash::from_engine(engine);

f.debug_tuple(stringify!($thing)).field(&format_args!("#{:016x}", hash)).finish()
// hex-conservative does not support truncation and this is the correct behaviour if
// a hash is considered integral type. So we truncate manually.
//
// > Precision
// > ...
// > For integral types, this is ignored.
//
// ref: https://doc.rust-lang.org/std/fmt/

struct Id([u8; 8]);

impl ::core::fmt::Display for Id {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
for byte in self.0.iter() {
write!(f, "{:02x}", byte)?;
}
Ok(())
}
}

let mut id = [0_u8; 8];
id.copy_from_slice(&hash[0..8]);
let id = Id(id);

f.debug_tuple(stringify!($thing)).field(&format_args!("#{}", id)).finish()
}
}

Expand Down

0 comments on commit a694b2c

Please sign in to comment.