1#![forbid(unsafe_code)]
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19pub enum ObjectFormat {
20 Sha1,
22 Sha256,
24}
25
26impl ObjectFormat {
27 pub const fn digest_len(self) -> usize {
29 match self {
30 Self::Sha1 => 20,
31 Self::Sha256 => 32,
32 }
33 }
34}
35
36#[derive(Clone, Copy, PartialEq, Eq, Hash)]
38pub struct Digest {
39 format: ObjectFormat,
40 bytes: [u8; 32],
41 len: u8,
42}
43
44impl Digest {
45 pub fn format(self) -> ObjectFormat {
46 self.format
47 }
48
49 pub fn as_bytes(&self) -> &[u8] {
50 &self.bytes[..self.len as usize]
51 }
52
53 pub fn from_bytes(format: ObjectFormat, bytes: &[u8]) -> Result<Self, HashError> {
54 let need = format.digest_len();
55 if bytes.len() != need {
56 return Err(HashError::DigestLength {
57 expected: need,
58 actual: bytes.len(),
59 });
60 }
61 let mut out = [0u8; 32];
62 out[..need].copy_from_slice(bytes);
63 Ok(Self {
64 format,
65 bytes: out,
66 len: need as u8,
67 })
68 }
69}
70
71impl core::fmt::Debug for Digest {
72 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
73 write!(f, "Digest({:?}, ", self.format)?;
74 for b in self.as_bytes() {
75 write!(f, "{b:02x}")?;
76 }
77 write!(f, ")")
78 }
79}
80
81#[derive(Clone)]
83pub struct Hasher {
84 inner: HasherInner,
85}
86
87#[derive(Clone)]
88enum HasherInner {
89 Sha1(Box<sha1collisiondetection::Sha1CD>),
92 Sha256(sha2::Sha256),
93}
94
95fn new_sha1cd() -> Box<sha1collisiondetection::Sha1CD> {
96 Box::new(
99 sha1collisiondetection::Builder::default()
100 .safe_hash(false)
101 .detect_collisions(true)
102 .use_ubc(true)
103 .build(),
104 )
105}
106
107impl Hasher {
108 pub fn new(format: ObjectFormat) -> Self {
109 let inner = match format {
110 ObjectFormat::Sha1 => HasherInner::Sha1(new_sha1cd()),
111 ObjectFormat::Sha256 => {
112 use sha2::Digest as _;
113 HasherInner::Sha256(sha2::Sha256::new())
114 }
115 };
116 Self { inner }
117 }
118
119 pub fn update(&mut self, data: &[u8]) {
120 match &mut self.inner {
121 HasherInner::Sha1(h) => {
122 sha1collisiondetection::Digest::update(h.as_mut(), data);
123 }
124 HasherInner::Sha256(h) => {
125 use sha2::Digest as _;
126 h.update(data);
127 }
128 }
129 }
130
131 pub fn finalize(self) -> Result<Digest, HashError> {
133 match self.inner {
134 HasherInner::Sha1(h) => {
135 let out = h.finalize_cd().map_err(|_| HashError::Sha1Collision)?;
136 Digest::from_bytes(ObjectFormat::Sha1, out.as_slice())
137 }
138 HasherInner::Sha256(h) => {
139 use sha2::Digest as _;
140 let out = h.finalize();
141 Digest::from_bytes(ObjectFormat::Sha256, out.as_slice())
142 }
143 }
144 }
145}
146
147pub fn hash_bytes(format: ObjectFormat, data: &[u8]) -> Result<Digest, HashError> {
149 let mut h = Hasher::new(format);
150 h.update(data);
151 h.finalize()
152}
153
154pub fn hash_object(
162 format: ObjectFormat,
163 type_name: &str,
164 payload: &[u8],
165) -> Result<Digest, HashError> {
166 let mut h = Hasher::new(format);
167 h.update(type_name.as_bytes());
168 h.update(b" ");
169 let mut size_buf = [0u8; 20];
170 let size = write_decimal(payload.len() as u64, &mut size_buf);
171 h.update(size);
172 h.update(&[0]);
173 h.update(payload);
174 h.finalize()
175}
176
177fn write_decimal(mut n: u64, buf: &mut [u8; 20]) -> &[u8] {
178 if n == 0 {
179 buf[19] = b'0';
180 return &buf[19..];
181 }
182 let mut i = 20;
183 while n > 0 {
184 i -= 1;
185 buf[i] = b'0' + (n % 10) as u8;
186 n /= 10;
187 }
188 &buf[i..]
189}
190
191#[derive(Debug, thiserror::Error, PartialEq, Eq)]
192pub enum HashError {
193 #[error("digest length mismatch: expected {expected}, got {actual}")]
194 DigestLength { expected: usize, actual: usize },
195 #[error(
198 "SHA-1 collision attack detected (OBJ-004 detect+refuse; immunity Impossible — use sha256 repos for transition)"
199 )]
200 Sha1Collision,
201}
202
203#[cfg(test)]
204mod tests {
205 use super::*;
206
207 const EMPTY_BLOB_SHA1: [u8; 20] = [
208 0xe6, 0x9d, 0xe2, 0x9b, 0xb2, 0xd1, 0xd6, 0x43, 0x4b, 0x8b, 0x29, 0xae, 0x77, 0x5a, 0xd8,
209 0xc2, 0xe4, 0x8c, 0x53, 0x91,
210 ];
211
212 #[test]
213 fn empty_blob_sha1_matches_known_oid() {
214 let d = hash_object(ObjectFormat::Sha1, "blob", b"").unwrap();
215 assert_eq!(d.as_bytes(), &EMPTY_BLOB_SHA1);
216 }
217
218 #[test]
219 fn hello_blob_sha1() {
220 let d = hash_object(ObjectFormat::Sha1, "blob", b"hello").unwrap();
221 assert_eq!(
222 hex::encode_lower(d.as_bytes()),
223 "b6fc4c620b67d95f953a5c1c1230aaab5db5a1b0"
224 );
225 }
226
227 #[test]
228 fn empty_blob_sha256_length_and_oid() {
229 let d = hash_object(ObjectFormat::Sha256, "blob", b"").unwrap();
230 assert_eq!(d.format(), ObjectFormat::Sha256);
231 assert_eq!(d.as_bytes().len(), 32);
232 assert_eq!(
233 hex::encode_lower(d.as_bytes()),
234 "473a0f4c3be8a93681a267e3b1e9a7dcda1185436fe141f7749120a303721813"
235 );
236 }
237
238 #[test]
239 fn hasher_incremental_matches_one_shot() {
240 let payload = b"incremental hashing must match one-shot";
241 let one_shot = hash_bytes(ObjectFormat::Sha1, payload).unwrap();
242
243 let mut h = Hasher::new(ObjectFormat::Sha1);
244 h.update(&payload[..10]);
245 h.update(&payload[10..20]);
246 h.update(&payload[20..]);
247 assert_eq!(h.finalize().unwrap(), one_shot);
248 }
249
250 #[test]
251 fn hash_object_incremental_matches_one_shot() {
252 let payload = b"split header and body updates";
253 let whole = hash_object(ObjectFormat::Sha1, "blob", payload).unwrap();
254
255 let mut h = Hasher::new(ObjectFormat::Sha1);
256 h.update(b"blob");
257 h.update(b" ");
258 h.update(payload.len().to_string().as_bytes());
259 h.update(&[0]);
260 h.update(&payload[..payload.len() / 2]);
261 h.update(&payload[payload.len() / 2..]);
262 assert_eq!(h.finalize().unwrap(), whole);
263 }
264
265 #[test]
266 fn digest_from_bytes_rejects_wrong_length() {
267 assert_eq!(
268 Digest::from_bytes(ObjectFormat::Sha1, &[0u8; 19]),
269 Err(HashError::DigestLength {
270 expected: 20,
271 actual: 19,
272 })
273 );
274 assert_eq!(
275 Digest::from_bytes(ObjectFormat::Sha256, &[0u8; 31]),
276 Err(HashError::DigestLength {
277 expected: 32,
278 actual: 31,
279 })
280 );
281 assert!(Digest::from_bytes(ObjectFormat::Sha1, &EMPTY_BLOB_SHA1).is_ok());
282 }
283
284 #[test]
285 fn nul_bytes_in_payload_are_hashed_as_payload() {
286 let payload = b"before\x00after";
287 let d = hash_object(ObjectFormat::Sha1, "blob", payload).unwrap();
288 let mut h = Hasher::new(ObjectFormat::Sha1);
289 h.update(b"blob");
290 h.update(b" ");
291 h.update(payload.len().to_string().as_bytes());
292 h.update(&[0]);
293 h.update(payload);
294 assert_eq!(d, h.finalize().unwrap());
295 assert_ne!(
296 d,
297 hash_object(ObjectFormat::Sha1, "blob", b"before").unwrap()
298 );
299 assert_ne!(
300 d,
301 hash_object(ObjectFormat::Sha1, "blob", b"beforeafter").unwrap()
302 );
303 }
304
305 #[test]
306 fn large_payload_stress() {
307 let payload: Vec<u8> = (0..64 * 1024).map(|i| (i % 251) as u8).collect();
308 let whole = hash_object(ObjectFormat::Sha1, "blob", &payload).unwrap();
309
310 let mut h = Hasher::new(ObjectFormat::Sha1);
311 h.update(b"blob");
312 h.update(b" ");
313 h.update(payload.len().to_string().as_bytes());
314 h.update(&[0]);
315 for chunk in payload.chunks(4096) {
316 h.update(chunk);
317 }
318 assert_eq!(h.finalize().unwrap(), whole);
319 }
320
321 #[test]
322 fn object_format_digest_len() {
323 assert_eq!(ObjectFormat::Sha1.digest_len(), 20);
324 assert_eq!(ObjectFormat::Sha256.digest_len(), 32);
325 }
326
327 #[test]
328 fn type_token_changes_oid() {
329 let payload = b"same-bytes";
330 let blob = hash_object(ObjectFormat::Sha1, "blob", payload).unwrap();
331 let tree = hash_object(ObjectFormat::Sha1, "tree", payload).unwrap();
332 let commit = hash_object(ObjectFormat::Sha1, "commit", payload).unwrap();
333 let tag = hash_object(ObjectFormat::Sha1, "tag", payload).unwrap();
334 assert_ne!(blob, tree);
335 assert_ne!(blob, commit);
336 assert_ne!(blob, tag);
337 assert_ne!(tree, commit);
338 }
339
340 #[test]
341 fn sha256_incremental_matches_one_shot() {
342 let payload = b"sha256 split updates";
343 let one = hash_bytes(ObjectFormat::Sha256, payload).unwrap();
344 let mut h = Hasher::new(ObjectFormat::Sha256);
345 h.update(&payload[..5]);
346 h.update(&payload[5..]);
347 assert_eq!(h.finalize().unwrap(), one);
348 assert_eq!(one.as_bytes().len(), 32);
349 }
350
351 #[test]
352 fn digest_wrong_format_length_pairs() {
353 assert!(Digest::from_bytes(ObjectFormat::Sha1, &[0u8; 32]).is_err());
354 assert!(Digest::from_bytes(ObjectFormat::Sha256, &[0u8; 20]).is_err());
355 }
356
357 #[test]
358 fn sha1_collision_error_message_names_obj004() {
359 let msg = HashError::Sha1Collision.to_string();
360 assert!(msg.contains("OBJ-004"));
361 assert!(msg.contains("detect+refuse"));
362 assert!(msg.contains("Impossible"));
363 }
364
365 #[test]
375 fn refuses_shattered_pdf_fixture_when_present() {
376 let path =
377 std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/shattered-1.pdf");
378 if !path.is_file() {
379 return;
380 }
381 let bytes = std::fs::read(&path).expect("read shattered fixture");
382 let err = hash_bytes(ObjectFormat::Sha1, &bytes).expect_err("must detect collision");
383 assert_eq!(err, HashError::Sha1Collision);
384 }
385}
386
387#[cfg(test)]
388mod hex {
389 pub fn encode_lower(bytes: &[u8]) -> String {
390 let mut s = String::with_capacity(bytes.len() * 2);
391 for b in bytes {
392 s.push_str(&format!("{b:02x}"));
393 }
394 s
395 }
396}