ssb_crypto/
hash.rs

1use core::mem::size_of;
2use zerocopy::{AsBytes, FromBytes};
3
4/// A sha256 hash digest. The standard hash in the scuttleverse.
5#[derive(AsBytes, FromBytes, PartialEq, Debug)]
6#[repr(C)]
7pub struct Hash(pub [u8; 32]);
8impl Hash {
9    /// The size in bytes of the Hash type ( == 32).
10    pub const SIZE: usize = size_of::<Self>();
11
12    /// Deserialize from byte representation.
13    /// Returns `None` if the slice length isn't 32.
14    /// Note that this doesn't hash the provided byte slice,
15    /// use the [`hash`] function for that.
16    pub fn from_slice(s: &[u8]) -> Option<Self> {
17        if s.len() == Self::SIZE {
18            let mut out = Self([0; Self::SIZE]);
19            out.0.copy_from_slice(s);
20            Some(out)
21        } else {
22            None
23        }
24    }
25
26    /// Deserialize from base-64 string representation.
27    /// Ignores optional leading '%' or '&' sigil and '.sha256' suffix.
28    ///
29    /// # Example
30    /// ```rust
31    /// let s = "%4hUgS4j0TwKdsZzOV/tfqiPtqoLw2qYg/Wl9Xy8FPEU=.sha256";
32    /// let h = ssb_crypto::Hash::from_base64(s).unwrap();
33    /// ```
34    #[cfg(feature = "b64")]
35    pub fn from_base64(mut s: &str) -> Option<Self> {
36        let mut buf = [0; Self::SIZE];
37        if s.starts_with('%') || s.starts_with('&') {
38            s = &s[1..];
39        }
40        if crate::b64::decode(s, &mut buf, Some(".sha256")) {
41            Some(Self(buf))
42        } else {
43            None
44        }
45    }
46
47    /// Does not include ".sha256" suffix or a sigil prefix.
48    ///
49    /// # Example
50    /// ```rust
51    /// let s = "4hUgS4j0TwKdsZzOV/tfqiPtqoLw2qYg/Wl9Xy8FPEU=";
52    /// let h = ssb_crypto::Hash::from_base64(s).unwrap();
53    /// assert_eq!(h.as_base64(), s);
54    /// ```
55    #[cfg(feature = "alloc")]
56    pub fn as_base64(&self) -> alloc::string::String {
57        base64::encode_config(&self.0[..], base64::STANDARD)
58    }
59}
60
61#[cfg(all(feature = "dalek", not(feature = "force_sodium")))]
62pub use crate::dalek::hash::hash;
63#[cfg(all(
64    feature = "sodium",
65    any(feature = "force_sodium", not(feature = "dalek"))
66))]
67pub use crate::sodium::hash::hash;