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)]
39#[as_ref(forward)]
40pub struct Sha256Hash([u8; 32]);
41
42impl Sha256Hash {
43    /// Create an instance by hashing a single input value.
44    pub fn hash_from(input: impl AsRef<[u8]>) -> Self {
45        let mut hasher = Sha256::new();
46        hasher.update(input);
47        Self(hasher.finalize().into())
48    }
49
50    /// Convert an existing hash into an instance of this type.
51    ///
52    /// Only basic length checking is performed!
53    pub fn from_existing_hash(hash: impl AsRef<[u8]>) -> CryptoKeystoreResult<Self> {
54        let array = hash.as_ref().try_into()?;
55        Ok(Self(array))
56    }
57}
58
59impl fmt::Display for Sha256Hash {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        let mut hex_bytes = [0; 64];
62        hex::encode_to_slice(self.0, hex_bytes.as_mut_slice())
63            .expect("infallible given inputs and outputs of fixed correct length");
64        let hex_str = str::from_utf8(&hex_bytes).expect("hex crate always produces valid utf8 data");
65        write!(f, "{hex_str}")
66    }
67}
68
69impl KeyType for Sha256Hash {
70    fn bytes(&self) -> std::borrow::Cow<'_, [u8]> {
71        (&self.0).into()
72    }
73}
74
75impl OwnedKeyType for Sha256Hash {
76    fn from_bytes(bytes: &[u8]) -> Option<Self> {
77        bytes.try_into().ok().map(Self)
78    }
79}
80
81#[cfg(not(target_family = "wasm"))]
82impl rusqlite::ToSql for Sha256Hash {
83    fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
84        self.as_ref().to_sql()
85    }
86}