core_crypto_keystore/
hash.rs1use std::fmt;
2
3use sha2::{Digest, Sha256};
4
5use crate::{
6 CryptoKeystoreResult,
7 traits::{KeyType, OwnedKeyType},
8};
9
10#[cfg(not(target_family = "wasm"))]
14pub(crate) fn sha256(data: &[u8]) -> String {
15 Sha256Hash::hash_from(data).to_string()
16}
17
18#[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 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 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}