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_container_bytes(format: ObjectFormat, data: &[u8]) -> Digest {
165 match format {
166 ObjectFormat::Sha1 => {
167 let out = ring::digest::digest(&ring::digest::SHA1_FOR_LEGACY_USE_ONLY, data);
168 Digest::from_bytes(ObjectFormat::Sha1, out.as_ref()).expect("20-byte sha1 digest")
169 }
170 ObjectFormat::Sha256 => {
171 let out = ring::digest::digest(&ring::digest::SHA256, data);
172 Digest::from_bytes(ObjectFormat::Sha256, out.as_ref()).expect("32-byte sha256 digest")
173 }
174 }
175}
176
177#[derive(Clone)]
188pub struct ContainerHasher {
189 format: ObjectFormat,
190 ctx: ring::digest::Context,
191}
192
193impl ContainerHasher {
194 pub fn new(format: ObjectFormat) -> Self {
196 let alg = match format {
197 ObjectFormat::Sha1 => &ring::digest::SHA1_FOR_LEGACY_USE_ONLY,
198 ObjectFormat::Sha256 => &ring::digest::SHA256,
199 };
200 Self {
201 format,
202 ctx: ring::digest::Context::new(alg),
203 }
204 }
205
206 pub fn update(&mut self, bytes: &[u8]) {
208 self.ctx.update(bytes);
209 }
210
211 pub fn finalize(self) -> Digest {
213 let out = self.ctx.finish();
214 let src = out.as_ref();
215 let need = self.format.digest_len();
216 let mut bytes = [0u8; 32];
217 let copy_len = src.len().min(need).min(bytes.len());
218 bytes[..copy_len].copy_from_slice(&src[..copy_len]);
219 Digest {
220 format: self.format,
221 bytes,
222 len: need as u8,
223 }
224 }
225}
226
227pub fn hash_object(
235 format: ObjectFormat,
236 type_name: &str,
237 payload: &[u8],
238) -> Result<Digest, HashError> {
239 let mut h = Hasher::new(format);
240 h.update(type_name.as_bytes());
241 h.update(b" ");
242 let mut size_buf = [0u8; 20];
243 let size = write_decimal(payload.len() as u64, &mut size_buf);
244 h.update(size);
245 h.update(&[0]);
246 h.update(payload);
247 h.finalize()
248}
249
250fn write_decimal(mut n: u64, buf: &mut [u8; 20]) -> &[u8] {
251 if n == 0 {
252 buf[19] = b'0';
253 return &buf[19..];
254 }
255 let mut i = 20;
256 while n > 0 {
257 i -= 1;
258 buf[i] = b'0' + (n % 10) as u8;
259 n /= 10;
260 }
261 &buf[i..]
262}
263
264#[derive(Debug, thiserror::Error, PartialEq, Eq)]
265pub enum HashError {
266 #[error("digest length mismatch: expected {expected}, got {actual}")]
267 DigestLength { expected: usize, actual: usize },
268 #[error(
271 "SHA-1 collision attack detected (OBJ-004 detect+refuse; immunity Impossible — use sha256 repos for transition)"
272 )]
273 Sha1Collision,
274}
275
276#[cfg(test)]
277mod tests {
278 use super::*;
279
280 const EMPTY_BLOB_SHA1: [u8; 20] = [
281 0xe6, 0x9d, 0xe2, 0x9b, 0xb2, 0xd1, 0xd6, 0x43, 0x4b, 0x8b, 0x29, 0xae, 0x77, 0x5a, 0xd8,
282 0xc2, 0xe4, 0x8c, 0x53, 0x91,
283 ];
284
285 #[test]
286 fn empty_blob_sha1_matches_known_oid() {
287 let d = hash_object(ObjectFormat::Sha1, "blob", b"").unwrap();
288 assert_eq!(d.as_bytes(), &EMPTY_BLOB_SHA1);
289 }
290
291 #[test]
292 fn hello_blob_sha1() {
293 let d = hash_object(ObjectFormat::Sha1, "blob", b"hello").unwrap();
294 assert_eq!(
295 hex::encode_lower(d.as_bytes()),
296 "b6fc4c620b67d95f953a5c1c1230aaab5db5a1b0"
297 );
298 }
299
300 #[test]
301 fn empty_blob_sha256_length_and_oid() {
302 let d = hash_object(ObjectFormat::Sha256, "blob", b"").unwrap();
303 assert_eq!(d.format(), ObjectFormat::Sha256);
304 assert_eq!(d.as_bytes().len(), 32);
305 assert_eq!(
306 hex::encode_lower(d.as_bytes()),
307 "473a0f4c3be8a93681a267e3b1e9a7dcda1185436fe141f7749120a303721813"
308 );
309 }
310
311 #[test]
312 fn hasher_incremental_matches_one_shot() {
313 let payload = b"incremental hashing must match one-shot";
314 let one_shot = hash_bytes(ObjectFormat::Sha1, payload).unwrap();
315
316 let mut h = Hasher::new(ObjectFormat::Sha1);
317 h.update(&payload[..10]);
318 h.update(&payload[10..20]);
319 h.update(&payload[20..]);
320 assert_eq!(h.finalize().unwrap(), one_shot);
321 }
322
323 #[test]
324 fn hash_object_incremental_matches_one_shot() {
325 let payload = b"split header and body updates";
326 let whole = hash_object(ObjectFormat::Sha1, "blob", payload).unwrap();
327
328 let mut h = Hasher::new(ObjectFormat::Sha1);
329 h.update(b"blob");
330 h.update(b" ");
331 h.update(payload.len().to_string().as_bytes());
332 h.update(&[0]);
333 h.update(&payload[..payload.len() / 2]);
334 h.update(&payload[payload.len() / 2..]);
335 assert_eq!(h.finalize().unwrap(), whole);
336 }
337
338 #[test]
339 fn digest_from_bytes_rejects_wrong_length() {
340 assert_eq!(
341 Digest::from_bytes(ObjectFormat::Sha1, &[0u8; 19]),
342 Err(HashError::DigestLength {
343 expected: 20,
344 actual: 19,
345 })
346 );
347 assert_eq!(
348 Digest::from_bytes(ObjectFormat::Sha256, &[0u8; 31]),
349 Err(HashError::DigestLength {
350 expected: 32,
351 actual: 31,
352 })
353 );
354 assert!(Digest::from_bytes(ObjectFormat::Sha1, &EMPTY_BLOB_SHA1).is_ok());
355 }
356
357 #[test]
358 fn nul_bytes_in_payload_are_hashed_as_payload() {
359 let payload = b"before\x00after";
360 let d = hash_object(ObjectFormat::Sha1, "blob", payload).unwrap();
361 let mut h = Hasher::new(ObjectFormat::Sha1);
362 h.update(b"blob");
363 h.update(b" ");
364 h.update(payload.len().to_string().as_bytes());
365 h.update(&[0]);
366 h.update(payload);
367 assert_eq!(d, h.finalize().unwrap());
368 assert_ne!(
369 d,
370 hash_object(ObjectFormat::Sha1, "blob", b"before").unwrap()
371 );
372 assert_ne!(
373 d,
374 hash_object(ObjectFormat::Sha1, "blob", b"beforeafter").unwrap()
375 );
376 }
377
378 #[test]
379 fn large_payload_stress() {
380 let payload: Vec<u8> = (0..64 * 1024).map(|i| (i % 251) as u8).collect();
381 let whole = hash_object(ObjectFormat::Sha1, "blob", &payload).unwrap();
382
383 let mut h = Hasher::new(ObjectFormat::Sha1);
384 h.update(b"blob");
385 h.update(b" ");
386 h.update(payload.len().to_string().as_bytes());
387 h.update(&[0]);
388 for chunk in payload.chunks(4096) {
389 h.update(chunk);
390 }
391 assert_eq!(h.finalize().unwrap(), whole);
392 }
393
394 #[test]
395 fn object_format_digest_len() {
396 assert_eq!(ObjectFormat::Sha1.digest_len(), 20);
397 assert_eq!(ObjectFormat::Sha256.digest_len(), 32);
398 }
399
400 #[test]
401 fn type_token_changes_oid() {
402 let payload = b"same-bytes";
403 let blob = hash_object(ObjectFormat::Sha1, "blob", payload).unwrap();
404 let tree = hash_object(ObjectFormat::Sha1, "tree", payload).unwrap();
405 let commit = hash_object(ObjectFormat::Sha1, "commit", payload).unwrap();
406 let tag = hash_object(ObjectFormat::Sha1, "tag", payload).unwrap();
407 assert_ne!(blob, tree);
408 assert_ne!(blob, commit);
409 assert_ne!(blob, tag);
410 assert_ne!(tree, commit);
411 }
412
413 #[test]
414 fn sha256_incremental_matches_one_shot() {
415 let payload = b"sha256 split updates";
416 let one = hash_bytes(ObjectFormat::Sha256, payload).unwrap();
417 let mut h = Hasher::new(ObjectFormat::Sha256);
418 h.update(&payload[..5]);
419 h.update(&payload[5..]);
420 assert_eq!(h.finalize().unwrap(), one);
421 assert_eq!(one.as_bytes().len(), 32);
422 }
423
424 #[test]
425 fn digest_wrong_format_length_pairs() {
426 assert!(Digest::from_bytes(ObjectFormat::Sha1, &[0u8; 32]).is_err());
427 assert!(Digest::from_bytes(ObjectFormat::Sha256, &[0u8; 20]).is_err());
428 }
429
430 #[test]
431 fn sha1_collision_error_message_names_obj004() {
432 let msg = HashError::Sha1Collision.to_string();
433 assert!(msg.contains("OBJ-004"));
434 assert!(msg.contains("detect+refuse"));
435 assert!(msg.contains("Impossible"));
436 }
437
438 #[test]
448 fn refuses_shattered_pdf_fixture_when_present() {
449 let path =
450 std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/shattered-1.pdf");
451 if !path.is_file() {
452 return;
453 }
454 let bytes = std::fs::read(&path).expect("read shattered fixture");
455 let err = hash_bytes(ObjectFormat::Sha1, &bytes).expect_err("must detect collision");
456 assert_eq!(err, HashError::Sha1Collision);
457 }
458
459 #[test]
460 fn container_hash_matches_standard_sha1_and_sha256_across_boundaries() {
461 for len in [0usize, 1, 3, 55, 56, 57, 63, 64, 65, 127, 128, 129, 65_536] {
462 let data: Vec<u8> = (0..len).map(|i| ((i * 31 + 7) % 251) as u8).collect();
463 assert_eq!(
464 hash_container_bytes(ObjectFormat::Sha1, &data),
465 hash_bytes(ObjectFormat::Sha1, &data).unwrap(),
466 "sha1 mismatch at len={len}"
467 );
468 assert_eq!(
469 hash_container_bytes(ObjectFormat::Sha256, &data),
470 hash_bytes(ObjectFormat::Sha256, &data).unwrap(),
471 "sha256 mismatch at len={len}"
472 );
473 }
474 }
475
476 #[test]
477 fn container_hasher_chunked_matches_hash_bytes_sha1_and_sha256() {
478 for format in [ObjectFormat::Sha1, ObjectFormat::Sha256] {
479 for len in [0usize, 1, 3, 55, 56, 57, 63, 64, 65, 127, 128, 129, 70_000] {
480 let data: Vec<u8> = (0..len).map(|i| ((i * 37 + 11) % 251) as u8).collect();
481 let expected = hash_bytes(format, &data).unwrap();
482 for chunk_size in [1usize, 7, 64, 4096] {
483 let mut h = ContainerHasher::new(format);
484 if data.is_empty() {
485 h.update(&[]);
486 } else {
487 for chunk in data.chunks(chunk_size) {
488 h.update(chunk);
489 }
490 }
491 let got = h.finalize();
492 assert_eq!(got.format(), format);
493 assert_eq!(got.as_bytes().len(), format.digest_len());
494 assert_eq!(
495 got, expected,
496 "mismatch for format={format:?} len={len} chunk={chunk_size}"
497 );
498 }
499 }
500 }
501 }
502}
503
504#[cfg(test)]
505mod hex {
506 pub fn encode_lower(bytes: &[u8]) -> String {
507 let mut s = String::with_capacity(bytes.len() * 2);
508 for b in bytes {
509 s.push_str(&format!("{b:02x}"));
510 }
511 s
512 }
513}