Skip to main content

capsule_core/crypto/
hash.rs

1//! SHA-256 content hashing — the one hash algorithm Capsule uses everywhere
2//! (content addressing, integrity verification, provenance chaining).
3//!
4//! SSoT: [Cryptography — Primitives § Cryptographic Hash]. The same SHA-256 value is
5//! reused across layers rather than recomputed — the content-addressing hash is the
6//! value the signed manifest commits to and the upload protocol declares and verifies.
7//!
8//! Hashing is **streaming** (incremental over chunks): the ciphertext hash of a large
9//! asset is computed as the STREAM chunks are produced, never by buffering the whole
10//! file. [`Sha256Hasher`] is the incremental interface; [`hash_bytes`] / [`hash_reader`]
11//! are the one-shot conveniences built on top of it.
12//!
13//! [Cryptography — Primitives § Cryptographic Hash]: https://docs/design/cryptography/primitives/#cryptographic-hash
14
15use std::io::{self, Read};
16
17use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
18use sha2::{Digest, Sha256};
19
20/// Length of a SHA-256 digest in bytes. Pinned by the `crypto_suite_id` inventory.
21pub const SHA256_LEN: usize = 32;
22
23/// A 32-byte SHA-256 digest.
24///
25/// Serializes as a CBOR **byte string** (major type 2), matching the `hash: bytes`
26/// fields in the manifest and sidecar schemas — never as an array of integers — so
27/// canonical encodings are byte-identical across implementations.
28#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
29pub struct Hash32(pub [u8; SHA256_LEN]);
30
31impl Hash32 {
32    /// Wrap raw digest bytes.
33    #[inline]
34    pub const fn from_bytes(bytes: [u8; SHA256_LEN]) -> Self {
35        Self(bytes)
36    }
37
38    /// Borrow the raw digest bytes.
39    #[inline]
40    pub const fn as_bytes(&self) -> &[u8; SHA256_LEN] {
41        &self.0
42    }
43
44    /// Lowercase hex encoding (64 chars).
45    pub fn to_hex(&self) -> String {
46        hex::encode(self.0)
47    }
48
49    /// Parse a 64-char lowercase/uppercase hex string into a digest.
50    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/// The provided string was not a valid 32-byte hex digest.
58#[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        // CBOR byte string, not a sequence of integers.
83        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                // Tolerate decoders that surface a byte string as a sequence.
103                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/// Incremental SHA-256 hasher: feed bytes with [`update`](Self::update), then
117/// [`finalize`](Self::finalize). Used to hash STREAM ciphertext as chunks are produced.
118#[derive(Clone, Default)]
119pub struct Sha256Hasher {
120    inner: Sha256,
121}
122
123impl Sha256Hasher {
124    /// A fresh hasher over the empty input.
125    pub fn new() -> Self {
126        Self::default()
127    }
128
129    /// Absorb a chunk of input.
130    #[inline]
131    pub fn update(&mut self, bytes: &[u8]) {
132        self.inner.update(bytes);
133    }
134
135    /// Consume the hasher and produce the digest.
136    pub fn finalize(self) -> Hash32 {
137        Hash32(self.inner.finalize().into())
138    }
139}
140
141/// One-shot SHA-256 of a byte slice.
142pub fn hash_bytes(bytes: &[u8]) -> Hash32 {
143    let mut h = Sha256Hasher::new();
144    h.update(bytes);
145    h.finalize()
146}
147
148/// Stream a reader to completion, hashing in 64 KiB blocks without buffering the whole input.
149pub 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;