optimize sha256 interface gather/vector inputs

Signed-off-by: Jason Volk <jason@zemos.net>
This commit is contained in:
Jason Volk 2024-11-15 22:20:28 +00:00
parent 14e3b242df
commit 887ae84f1e
7 changed files with 85 additions and 50 deletions

View file

@ -1,13 +1,10 @@
mod argon;
mod sha256;
pub mod sha256;
use crate::Result;
pub fn password(password: &str) -> Result<String> { argon::password(password) }
pub fn verify_password(password: &str, password_hash: &str) -> Result<()> {
pub fn verify_password(password: &str, password_hash: &str) -> Result {
argon::verify_password(password, password_hash)
}
#[must_use]
pub fn calculate_hash(keys: &[&[u8]]) -> Vec<u8> { sha256::hash(keys) }
pub fn password(password: &str) -> Result<String> { argon::password(password) }

View file

@ -1,9 +1,62 @@
use ring::{digest, digest::SHA256};
use ring::{
digest,
digest::{Context, SHA256, SHA256_OUTPUT_LEN},
};
#[tracing::instrument(skip_all, level = "debug")]
pub(super) fn hash(keys: &[&[u8]]) -> Vec<u8> {
// We only hash the pdu's event ids, not the whole pdu
let bytes = keys.join(&0xFF);
let hash = digest::digest(&SHA256, &bytes);
hash.as_ref().to_owned()
pub type Digest = [u8; SHA256_OUTPUT_LEN];
/// Sha256 hash (input gather joined by 0xFF bytes)
#[must_use]
#[tracing::instrument(skip(inputs), level = "trace")]
pub fn delimited<'a, T, I>(mut inputs: I) -> Digest
where
I: Iterator<Item = T> + 'a,
T: AsRef<[u8]> + 'a,
{
let mut ctx = Context::new(&SHA256);
if let Some(input) = inputs.next() {
ctx.update(input.as_ref());
for input in inputs {
ctx.update(b"\xFF");
ctx.update(input.as_ref());
}
}
ctx.finish()
.as_ref()
.try_into()
.expect("failed to return Digest buffer")
}
/// Sha256 hash (input gather)
#[must_use]
#[tracing::instrument(skip(inputs), level = "trace")]
pub fn concat<'a, T, I>(inputs: I) -> Digest
where
I: Iterator<Item = T> + 'a,
T: AsRef<[u8]> + 'a,
{
inputs
.fold(Context::new(&SHA256), |mut ctx, input| {
ctx.update(input.as_ref());
ctx
})
.finish()
.as_ref()
.try_into()
.expect("failed to return Digest buffer")
}
/// Sha256 hash
#[inline]
#[must_use]
#[tracing::instrument(skip(input), level = "trace")]
pub fn hash<T>(input: T) -> Digest
where
T: AsRef<[u8]>,
{
digest::digest(&SHA256, input.as_ref())
.as_ref()
.try_into()
.expect("failed to return Digest buffer")
}

View file

@ -28,7 +28,7 @@ pub use self::{
bytes::{increment, u64_from_bytes, u64_from_u8, u64_from_u8x8},
debug::slice_truncated as debug_slice_truncated,
future::TryExtExt as TryFutureExtExt,
hash::calculate_hash,
hash::sha256::delimited as calculate_hash,
html::Escape as HtmlEscape,
json::{deserialize_from_str, to_canonical_object},
math::clamp,