Convert the content to the report data with a specific hash algorithm.
(&self, content: &[u8], hash: &str)
| 250 | |
| 251 | /// Convert the content to the report data with a specific hash algorithm. |
| 252 | pub fn to_report_data_with_hash(&self, content: &[u8], hash: &str) -> Result<[u8; 64]> { |
| 253 | macro_rules! do_hash { |
| 254 | ($hash: ty) => {{ |
| 255 | // The format is: |
| 256 | // hash(<tag>:<content>) |
| 257 | let mut hasher = <$hash>::new(); |
| 258 | hasher.update(self.tag().as_bytes()); |
| 259 | hasher.update(b":"); |
| 260 | hasher.update(content); |
| 261 | let output = hasher.finalize(); |
| 262 | |
| 263 | let mut padded = [0u8; 64]; |
| 264 | padded[..output.len()].copy_from_slice(&output); |
| 265 | padded |
| 266 | }}; |
| 267 | } |
| 268 | let hash = if hash.is_empty() { |
| 269 | DEFAULT_HASH_ALGORITHM |
| 270 | } else { |
| 271 | hash |
| 272 | }; |
| 273 | let output = match hash { |
| 274 | "sha256" => do_hash!(sha2::Sha256), |
| 275 | "sha384" => do_hash!(sha2::Sha384), |
| 276 | "sha512" => do_hash!(sha2::Sha512), |
| 277 | "sha3-256" => do_hash!(sha3::Sha3_256), |
| 278 | "sha3-384" => do_hash!(sha3::Sha3_384), |
| 279 | "sha3-512" => do_hash!(sha3::Sha3_512), |
| 280 | "keccak256" => do_hash!(sha3::Keccak256), |
| 281 | "keccak384" => do_hash!(sha3::Keccak384), |
| 282 | "keccak512" => do_hash!(sha3::Keccak512), |
| 283 | "raw" => content.try_into().ok().context("invalid content length")?, |
| 284 | _ => bail!("invalid hash algorithm"), |
| 285 | }; |
| 286 | Ok(output) |
| 287 | } |
| 288 | } |
| 289 | |
| 290 | #[allow(clippy::large_enum_variant)] |
no test coverage detected