core_crypto_keystore/
hash.rs1use std::fmt;
2
3use sha2::{Digest, Sha256};
4
5use crate::{CryptoKeystoreResult, traits::KeyType};
6
7#[cfg(not(target_family = "wasm"))]
11pub(crate) fn sha256(data: &[u8]) -> String {
12 Sha256Hash::hash_from(data).to_string()
13}
14
15#[derive(
22 Debug,
23 Default,
24 Clone,
25 Copy,
26 PartialEq,
27 Eq,
28 PartialOrd,
29 Ord,
30 Hash,
31 derive_more::Deref,
32 derive_more::AsRef,
33 derive_more::From,
34 derive_more::Into,
35)]
36#[as_ref(forward)]
37pub struct Sha256Hash([u8; 32]);
38
39impl Sha256Hash {
40 pub fn hash_from(input: impl AsRef<[u8]>) -> Self {
42 let mut hasher = Sha256::new();
43 hasher.update(input);
44 Self(hasher.finalize().into())
45 }
46
47 pub fn from_existing_hash(hash: impl AsRef<[u8]>) -> CryptoKeystoreResult<Self> {
51 let array = hash.as_ref().try_into()?;
52 Ok(Self(array))
53 }
54}
55
56impl fmt::Display for Sha256Hash {
57 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58 let mut hex_bytes = [0; 64];
59 hex::encode_to_slice(self.0, hex_bytes.as_mut_slice())
60 .expect("infallible given inputs and outputs of fixed correct length");
61 let hex_str = str::from_utf8(&hex_bytes).expect("hex crate always produces valid utf8 data");
62 write!(f, "{hex_str}")
63 }
64}
65
66impl KeyType for Sha256Hash {
67 fn bytes(&self) -> std::borrow::Cow<'_, [u8]> {
68 (&self.0).into()
69 }
70}
71
72#[cfg(not(target_family = "wasm"))]
73impl rusqlite::ToSql for Sha256Hash {
74 fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
75 self.as_ref().to_sql()
76 }
77}