Skip to main content

kbs_types/
hash_algorithm.rs

1use serde::{Deserialize, Serialize};
2use sha2::{Digest, Sha256, Sha384, Sha512};
3use sm3::Sm3;
4use strum::{AsRefStr, Display, EnumString};
5
6#[cfg(all(feature = "alloc", not(feature = "std")))]
7use alloc::{vec, vec::Vec};
8
9/// Hash algorithms used to calculate runtime/init data binding
10#[derive(
11    Debug, Clone, Copy, PartialEq, Serialize, Deserialize, AsRefStr, Display, EnumString, Default,
12)]
13#[serde(rename_all = "lowercase")]
14pub enum HashAlgorithm {
15    #[strum(ascii_case_insensitive)]
16    #[strum(serialize = "sha256")]
17    Sha256,
18
19    #[strum(ascii_case_insensitive)]
20    #[strum(serialize = "sha384")]
21    #[default]
22    Sha384,
23
24    #[strum(ascii_case_insensitive)]
25    #[strum(serialize = "sha512")]
26    Sha512,
27
28    #[strum(ascii_case_insensitive)]
29    #[strum(serialize = "sm3")]
30    Sm3,
31}
32
33fn hash_reportdata<D: Digest>(material: &[u8]) -> Vec<u8> {
34    D::new().chain_update(material).finalize().to_vec()
35}
36
37impl HashAlgorithm {
38    /// Return the hash value length in bytes
39    pub fn digest_len(&self) -> usize {
40        match self {
41            HashAlgorithm::Sha256 => 32,
42            HashAlgorithm::Sha384 => 48,
43            HashAlgorithm::Sha512 => 64,
44            HashAlgorithm::Sm3 => 32,
45        }
46    }
47
48    pub fn digest(&self, material: &[u8]) -> Vec<u8> {
49        match self {
50            HashAlgorithm::Sha256 => hash_reportdata::<Sha256>(material),
51            HashAlgorithm::Sha384 => hash_reportdata::<Sha384>(material),
52            HashAlgorithm::Sha512 => hash_reportdata::<Sha512>(material),
53            HashAlgorithm::Sm3 => hash_reportdata::<Sm3>(material),
54        }
55    }
56
57    /// Return a list of all supported hash algorithms.
58    pub fn list_all() -> Vec<Self> {
59        vec![
60            HashAlgorithm::Sha256,
61            HashAlgorithm::Sha384,
62            HashAlgorithm::Sha512,
63            HashAlgorithm::Sm3,
64        ]
65    }
66}