core_crypto_keystore/
hash.rs

1use std::fmt;
2
3use sha2::{Digest, Sha256};
4
5use crate::{
6    CryptoKeystoreResult,
7    traits::{KeyType, OwnedKeyType},
8};
9
10/// Used to calculate ID hashes for some MlsEntities' SQLite tables (not used on wasm).
11/// We only use sha256 on platforms where we use SQLite.
12/// On wasm, we use IndexedDB, a key-value store, via the idb crate.
13#[cfg(not(target_family = "wasm"))]
14pub(crate) fn sha256(data: &[u8]) -> String {
15    Sha256Hash::hash_from(data).to_string()
16}
17
18/// A Sha256 hash.
19///
20/// Certain entities use this kind of hash as a key. It's a small value which lives on the stack,
21/// as opposed to the longer, heap-allocated values which it replaces.
22///
23/// This type enables this use case with the new entity traits.
24#[derive(
25    Debug,
26    Default,
27    Clone,
28    Copy,
29    PartialEq,
30    Eq,
31    PartialOrd,
32    Ord,
33    Hash,
34    derive_more::Deref,
35    derive_more::AsRef,
36    derive_more::From,
37    derive_more::Into,
38    serde::Serialize,
39)]
40#[as_ref(forward)]
41pub struct Sha256Hash([u8; 32]);
42
43impl Sha256Hash {
44    /// Create an instance by hashing a single input value.
45    pub fn hash_from(input: impl AsRef<[u8]>) -> Self {
46        let mut hasher = Sha256::new();
47        hasher.update(input);
48        Self(hasher.finalize().into())
49    }
50
51    /// Convert an existing hash into an instance of this type.
52    ///
53    /// Only basic length checking is performed!
54    pub fn from_existing_hash(hash: impl AsRef<[u8]>) -> CryptoKeystoreResult<Self> {
55        let array = hash.as_ref().try_into()?;
56        Ok(Self(array))
57    }
58}
59
60impl fmt::Display for Sha256Hash {
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        let mut hex_bytes = [0; 64];
63        hex::encode_to_slice(self.0, hex_bytes.as_mut_slice())
64            .expect("infallible given inputs and outputs of fixed correct length");
65        let hex_str = str::from_utf8(&hex_bytes).expect("hex crate always produces valid utf8 data");
66        write!(f, "{hex_str}")
67    }
68}
69
70impl KeyType for Sha256Hash {
71    fn bytes(&self) -> std::borrow::Cow<'_, [u8]> {
72        (&self.0).into()
73    }
74}
75
76impl OwnedKeyType for Sha256Hash {
77    fn from_bytes(bytes: &[u8]) -> Option<Self> {
78        bytes.try_into().ok().map(Self)
79    }
80}
81
82#[cfg(not(target_family = "wasm"))]
83impl rusqlite::ToSql for Sha256Hash {
84    fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
85        self.as_ref().to_sql()
86    }
87}