Initial import and port from C++ code.

This commit is contained in:
2025-12-28 13:45:13 -07:00
commit ddf44d7e33
13 changed files with 1165 additions and 0 deletions

95
src/lib.rs Normal file
View File

@@ -0,0 +1,95 @@
//! emsha is the embedded hashing library. It aims to work even in
//! nostdenv environments.
#![no_std]
use core::error;
use core::fmt;
#[derive(Clone, Debug)]
pub struct Error {
reason: Code,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.reason {
Code::Unknown => write!(f, "unknown error"),
Code::OK => write!(f, "OK"),
Code::TestFailure => write!(f, "test failure"),
Code::InvalidState => write!(f, "invalid state"),
Code::InputTooLong => write!(f, "input is too long"),
Code::BufferTooSmall => {
write!(f, "output buffer too small")
}
Code::HashNotFinalized => {
write!(f, "hash has not been finalized")
}
}
}
}
impl Error {
pub fn with(reason: Code) -> Self {
Self { reason }
}
}
impl error::Error for Error {}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Code {
Unknown,
OK,
TestFailure,
InvalidState,
InputTooLong,
BufferTooSmall,
HashNotFinalized,
}
pub type Result<T> = core::result::Result<T, Error>;
pub trait Hash {
/// Bring the Hash back to its initial state.
///
/// That is, the idea is that
///
/// `hash.reset();`
/// `hash.update(...);`
/// `hash.result(...);`
///
/// is idempotent, assuming the inputs to update and result are
/// constant. The implications of this for a given implementer
/// should be described in that type's documentation, but in
/// general, it has the effect of preserving any initial state
/// while removing any data written to the Hash via the update
/// method.
fn reset(&mut self) -> Result<()>;
/// Write message data into the Hash.
fn update(&mut self, msg: &[u8]) -> Result<()>;
/// Carry out any final operations on the Hash.
///
/// After a call to finalize, no more data can be written.
/// Additionally, it transfers out the resulting hash into its
/// argument.
fn finalize(&mut self, digest: &mut [u8]) -> Result<()>;
/// Transfers out the hash to the argument.
///
/// The Hash must keep enough state for repeated calls to result
/// to work.
fn result(&self, digest: &mut [u8]) -> Result<()>;
/// Return the output size of the Hash.
///
/// This is how large the buffers written to by result should
/// be.
fn size() -> usize;
}
mod common;
pub mod hmac;
pub mod sha256;