capsule_core/crypto/
hash.rs1use std::io::{self, Read};
16
17use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
18use sha2::{Digest, Sha256};
19
20pub const SHA256_LEN: usize = 32;
22
23#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
29pub struct Hash32(pub [u8; SHA256_LEN]);
30
31impl Hash32 {
32 #[inline]
34 pub const fn from_bytes(bytes: [u8; SHA256_LEN]) -> Self {
35 Self(bytes)
36 }
37
38 #[inline]
40 pub const fn as_bytes(&self) -> &[u8; SHA256_LEN] {
41 &self.0
42 }
43
44 pub fn to_hex(&self) -> String {
46 hex::encode(self.0)
47 }
48
49 pub fn from_hex(s: &str) -> Result<Self, FromHexError> {
51 let v = hex::decode(s).map_err(|_| FromHexError)?;
52 let arr: [u8; SHA256_LEN] = v.as_slice().try_into().map_err(|_| FromHexError)?;
53 Ok(Self(arr))
54 }
55}
56
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub struct FromHexError;
60
61impl std::fmt::Display for FromHexError {
62 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63 f.write_str("invalid 32-byte hex digest")
64 }
65}
66impl std::error::Error for FromHexError {}
67
68impl std::fmt::Debug for Hash32 {
69 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70 write!(f, "Hash32({})", self.to_hex())
71 }
72}
73
74impl std::fmt::Display for Hash32 {
75 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76 f.write_str(&self.to_hex())
77 }
78}
79
80impl Serialize for Hash32 {
81 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
82 s.serialize_bytes(&self.0)
84 }
85}
86
87impl<'de> Deserialize<'de> for Hash32 {
88 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
89 struct V;
90 impl<'de> de::Visitor<'de> for V {
91 type Value = Hash32;
92 fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
93 f.write_str("a 32-byte SHA-256 digest")
94 }
95 fn visit_bytes<E: de::Error>(self, v: &[u8]) -> Result<Hash32, E> {
96 let arr: [u8; SHA256_LEN] = v
97 .try_into()
98 .map_err(|_| E::invalid_length(v.len(), &"32 bytes"))?;
99 Ok(Hash32(arr))
100 }
101 fn visit_seq<A: de::SeqAccess<'de>>(self, mut seq: A) -> Result<Hash32, A::Error> {
102 let mut arr = [0u8; SHA256_LEN];
104 for (i, slot) in arr.iter_mut().enumerate() {
105 *slot = seq
106 .next_element()?
107 .ok_or_else(|| de::Error::invalid_length(i, &"32 bytes"))?;
108 }
109 Ok(Hash32(arr))
110 }
111 }
112 d.deserialize_bytes(V)
113 }
114}
115
116#[derive(Clone, Default)]
119pub struct Sha256Hasher {
120 inner: Sha256,
121}
122
123impl Sha256Hasher {
124 pub fn new() -> Self {
126 Self::default()
127 }
128
129 #[inline]
131 pub fn update(&mut self, bytes: &[u8]) {
132 self.inner.update(bytes);
133 }
134
135 pub fn finalize(self) -> Hash32 {
137 Hash32(self.inner.finalize().into())
138 }
139}
140
141pub fn hash_bytes(bytes: &[u8]) -> Hash32 {
143 let mut h = Sha256Hasher::new();
144 h.update(bytes);
145 h.finalize()
146}
147
148pub fn hash_reader<R: Read>(mut reader: R) -> io::Result<Hash32> {
150 let mut hasher = Sha256Hasher::new();
151 let mut buf = vec![0u8; 64 * 1024];
152 loop {
153 let n = reader.read(&mut buf)?;
154 if n == 0 {
155 break;
156 }
157 hasher.update(&buf[..n]);
158 }
159 Ok(hasher.finalize())
160}
161
162#[cfg(test)]
163mod tests;