diff --git a/Cargo.toml b/Cargo.toml index c0a1934..d3504a4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,6 +19,8 @@ base64 = { version = "0.22.1", default-features = false } serde = { version = "1.0", default-features = false, features = ["derive"] } serde_json = { version = "1.0", default-features = false } sev = { version = "6.0.0", features = ["openssl"], optional = true } +sha2 = "0.10" +strum = { version = "0.27", features = ["derive"] } thiserror = { version = "2.0.3", default-features = false } [dev-dependencies] diff --git a/src/hash_algorithm.rs b/src/hash_algorithm.rs new file mode 100644 index 0000000..dbddcba --- /dev/null +++ b/src/hash_algorithm.rs @@ -0,0 +1,61 @@ +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256, Sha384, Sha512}; +use strum::{AsRefStr, Display, EnumString}; + +#[cfg(all(feature = "alloc", not(feature = "std")))] +use alloc::{vec, vec::Vec}; + +/// Hash algorithms used to calculate runtime/init data binding +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, AsRefStr, Display, EnumString)] +#[serde(rename_all = "lowercase")] +pub enum HashAlgorithm { + #[strum(ascii_case_insensitive)] + #[strum(serialize = "sha256")] + Sha256, + + #[strum(ascii_case_insensitive)] + #[strum(serialize = "sha384")] + Sha384, + + #[strum(ascii_case_insensitive)] + #[strum(serialize = "sha512")] + Sha512, +} + +impl Default for HashAlgorithm { + fn default() -> Self { + Self::Sha384 + } +} + +fn hash_reportdata(material: &[u8]) -> Vec { + D::new().chain_update(material).finalize().to_vec() +} + +impl HashAlgorithm { + /// Return the hash value length in bytes + pub fn digest_len(&self) -> usize { + match self { + HashAlgorithm::Sha256 => 32, + HashAlgorithm::Sha384 => 48, + HashAlgorithm::Sha512 => 64, + } + } + + pub fn digest(&self, material: &[u8]) -> Vec { + match self { + HashAlgorithm::Sha256 => hash_reportdata::(material), + HashAlgorithm::Sha384 => hash_reportdata::(material), + HashAlgorithm::Sha512 => hash_reportdata::(material), + } + } + + /// Return a list of all supported hash algorithms. + pub fn list_all() -> Vec { + vec![ + HashAlgorithm::Sha256, + HashAlgorithm::Sha384, + HashAlgorithm::Sha512, + ] + } +} diff --git a/src/lib.rs b/src/lib.rs index 6827882..3cea258 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -8,6 +8,9 @@ extern crate alloc; mod error; pub use error::{KbsTypesError, Result}; +mod hash_algorithm; +pub use hash_algorithm::HashAlgorithm; + #[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::{string::String, vec::Vec}; use base64::{prelude::BASE64_URL_SAFE_NO_PAD, Engine}; @@ -247,7 +250,7 @@ mod tests { use crate::*; #[cfg(all(feature = "alloc", not(feature = "std")))] - use alloc::{collections::btree_map::BTreeMap, string::ToString}; + use alloc::string::ToString; #[test] fn parse_request() {