From c73df68e15af74fc7763b758e1782e01630f2362 Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 5 Jan 2024 16:29:41 +0800 Subject: [PATCH] add sha512-digest wrapper class this is a trait wrapper that allows us to take pre-hash as a `[u8]` and wrap it into a thing that hase a finalize() method and the requisite traits to satisfy Rust, allowing us to pass our loader-generated, environment-variable-passed hash into an otherwise unawares cryptography crate. mea culpa. --- services/root-keys/src/main.rs | 1 + services/root-keys/src/sha512_digest.rs | 59 +++++++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 services/root-keys/src/sha512_digest.rs diff --git a/services/root-keys/src/main.rs b/services/root-keys/src/main.rs index cfb5df982..4c22e106c 100644 --- a/services/root-keys/src/main.rs +++ b/services/root-keys/src/main.rs @@ -4,6 +4,7 @@ mod api; use api::*; mod backups; +mod sha512_digest; use xous::{msg_scalar_unpack, send_message, msg_blocking_scalar_unpack}; #[cfg(feature = "policy-menu")] diff --git a/services/root-keys/src/sha512_digest.rs b/services/root-keys/src/sha512_digest.rs new file mode 100644 index 000000000..19174a981 --- /dev/null +++ b/services/root-keys/src/sha512_digest.rs @@ -0,0 +1,59 @@ +use digest::{ + consts::{U64, U128}, + BlockInput, + FixedOutputDirty, + Reset, + Update, +}; + +/// Wrap a pre-hash value in a Digest trait +#[derive(Clone)] +pub struct Sha512Prehash { + /// track the length of the message processed so far + hash: Option<[u8; 64]> +} +impl Sha512Prehash { + // use this function instead of default for more control over configuration of the hardware engine + pub fn new() -> Self { + Sha512Prehash { + hash: None + } + } + pub fn set_prehash(&mut self, hash: [u8; 64]) { + self.hash = Some(hash); + } +} +impl Default for Sha512Prehash { + fn default() -> Self { + Sha512Prehash::new() + } +} + +impl BlockInput for Sha512Prehash { + type BlockSize = U128; +} + +impl Update for Sha512Prehash { + fn update(&mut self, _input: impl AsRef<[u8]>) { + panic!("Prehash implementation cannot process any new data"); + } +} + +impl FixedOutputDirty for Sha512Prehash { + type OutputSize = U64; + + fn finalize_into_dirty(&mut self, out: &mut digest::Output) { + if let Some(hash) = self.hash { + for (dest, &src) in out.chunks_exact_mut(1).zip(hash.iter()) { + dest.copy_from_slice(&[src]) + } + } else { + panic!("Sha512Prehash object was not initialized with a pre-hash value before use!"); + } + } +} + +impl Reset for Sha512Prehash { + fn reset(&mut self) { + } +} \ No newline at end of file