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