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
177pub fn hash_object(
185 format: ObjectFormat,
186 type_name: &str,
187 payload: &[u8],
188) -> Result<Digest, HashError> {
189 let mut h = Hasher::new(format);
190 h.update(type_name.as_bytes());
191 h.update(b" ");
192 let mut size_buf = [0u8; 20];
193 let size = write_decimal(payload.len() as u64, &mut size_buf);
194 h.update(size);
195 h.update(&[0]);
196 h.update(payload);
197 h.finalize()
198}
199
200fn write_decimal(mut n: u64, buf: &mut [u8; 20]) -> &[u8] {
201 if n == 0 {
202 buf[19] = b'0';
203 return &buf[19..];
204 }
205 let mut i = 20;
206 while n > 0 {
207 i -= 1;
208 buf[i] = b'0' + (n % 10) as u8;
209 n /= 10;
210 }
211 &buf[i..]
212}
213
214#[derive(Debug, thiserror::Error, PartialEq, Eq)]
215pub enum HashError {
216 #[error("digest length mismatch: expected {expected}, got {actual}")]
217 DigestLength { expected: usize, actual: usize },
218 #[error(
221 "SHA-1 collision attack detected (OBJ-004 detect+refuse; immunity Impossible — use sha256 repos for transition)"
222 )]
223 Sha1Collision,
224}
225
226#[cfg(test)]
227mod tests {
228 use super::*;
229
230 const EMPTY_BLOB_SHA1: [u8; 20] = [
231 0xe6, 0x9d, 0xe2, 0x9b, 0xb2, 0xd1, 0xd6, 0x43, 0x4b, 0x8b, 0x29, 0xae, 0x77, 0x5a, 0xd8,
232 0xc2, 0xe4, 0x8c, 0x53, 0x91,
233 ];
234
235 #[test]
236 fn empty_blob_sha1_matches_known_oid() {
237 let d = hash_object(ObjectFormat::Sha1, "blob", b"").unwrap();
238 assert_eq!(d.as_bytes(), &EMPTY_BLOB_SHA1);
239 }
240
241 #[test]
242 fn hello_blob_sha1() {
243 let d = hash_object(ObjectFormat::Sha1, "blob", b"hello").unwrap();
244 assert_eq!(
245 hex::encode_lower(d.as_bytes()),
246 "b6fc4c620b67d95f953a5c1c1230aaab5db5a1b0"
247 );
248 }
249
250 #[test]
251 fn empty_blob_sha256_length_and_oid() {
252 let d = hash_object(ObjectFormat::Sha256, "blob", b"").unwrap();
253 assert_eq!(d.format(), ObjectFormat::Sha256);
254 assert_eq!(d.as_bytes().len(), 32);
255 assert_eq!(
256 hex::encode_lower(d.as_bytes()),
257 "473a0f4c3be8a93681a267e3b1e9a7dcda1185436fe141f7749120a303721813"
258 );
259 }
260
261 #[test]
262 fn hasher_incremental_matches_one_shot() {
263 let payload = b"incremental hashing must match one-shot";
264 let one_shot = hash_bytes(ObjectFormat::Sha1, payload).unwrap();
265
266 let mut h = Hasher::new(ObjectFormat::Sha1);
267 h.update(&payload[..10]);
268 h.update(&payload[10..20]);
269 h.update(&payload[20..]);
270 assert_eq!(h.finalize().unwrap(), one_shot);
271 }
272
273 #[test]
274 fn hash_object_incremental_matches_one_shot() {
275 let payload = b"split header and body updates";
276 let whole = hash_object(ObjectFormat::Sha1, "blob", payload).unwrap();
277
278 let mut h = Hasher::new(ObjectFormat::Sha1);
279 h.update(b"blob");
280 h.update(b" ");
281 h.update(payload.len().to_string().as_bytes());
282 h.update(&[0]);
283 h.update(&payload[..payload.len() / 2]);
284 h.update(&payload[payload.len() / 2..]);
285 assert_eq!(h.finalize().unwrap(), whole);
286 }
287
288 #[test]
289 fn digest_from_bytes_rejects_wrong_length() {
290 assert_eq!(
291 Digest::from_bytes(ObjectFormat::Sha1, &[0u8; 19]),
292 Err(HashError::DigestLength {
293 expected: 20,
294 actual: 19,
295 })
296 );
297 assert_eq!(
298 Digest::from_bytes(ObjectFormat::Sha256, &[0u8; 31]),
299 Err(HashError::DigestLength {
300 expected: 32,
301 actual: 31,
302 })
303 );
304 assert!(Digest::from_bytes(ObjectFormat::Sha1, &EMPTY_BLOB_SHA1).is_ok());
305 }
306
307 #[test]
308 fn nul_bytes_in_payload_are_hashed_as_payload() {
309 let payload = b"before\x00after";
310 let d = hash_object(ObjectFormat::Sha1, "blob", payload).unwrap();
311 let mut h = Hasher::new(ObjectFormat::Sha1);
312 h.update(b"blob");
313 h.update(b" ");
314 h.update(payload.len().to_string().as_bytes());
315 h.update(&[0]);
316 h.update(payload);
317 assert_eq!(d, h.finalize().unwrap());
318 assert_ne!(
319 d,
320 hash_object(ObjectFormat::Sha1, "blob", b"before").unwrap()
321 );
322 assert_ne!(
323 d,
324 hash_object(ObjectFormat::Sha1, "blob", b"beforeafter").unwrap()
325 );
326 }
327
328 #[test]
329 fn large_payload_stress() {
330 let payload: Vec<u8> = (0..64 * 1024).map(|i| (i % 251) as u8).collect();
331 let whole = hash_object(ObjectFormat::Sha1, "blob", &payload).unwrap();
332
333 let mut h = Hasher::new(ObjectFormat::Sha1);
334 h.update(b"blob");
335 h.update(b" ");
336 h.update(payload.len().to_string().as_bytes());
337 h.update(&[0]);
338 for chunk in payload.chunks(4096) {
339 h.update(chunk);
340 }
341 assert_eq!(h.finalize().unwrap(), whole);
342 }
343
344 #[test]
345 fn object_format_digest_len() {
346 assert_eq!(ObjectFormat::Sha1.digest_len(), 20);
347 assert_eq!(ObjectFormat::Sha256.digest_len(), 32);
348 }
349
350 #[test]
351 fn type_token_changes_oid() {
352 let payload = b"same-bytes";
353 let blob = hash_object(ObjectFormat::Sha1, "blob", payload).unwrap();
354 let tree = hash_object(ObjectFormat::Sha1, "tree", payload).unwrap();
355 let commit = hash_object(ObjectFormat::Sha1, "commit", payload).unwrap();
356 let tag = hash_object(ObjectFormat::Sha1, "tag", payload).unwrap();
357 assert_ne!(blob, tree);
358 assert_ne!(blob, commit);
359 assert_ne!(blob, tag);
360 assert_ne!(tree, commit);
361 }
362
363 #[test]
364 fn sha256_incremental_matches_one_shot() {
365 let payload = b"sha256 split updates";
366 let one = hash_bytes(ObjectFormat::Sha256, payload).unwrap();
367 let mut h = Hasher::new(ObjectFormat::Sha256);
368 h.update(&payload[..5]);
369 h.update(&payload[5..]);
370 assert_eq!(h.finalize().unwrap(), one);
371 assert_eq!(one.as_bytes().len(), 32);
372 }
373
374 #[test]
375 fn digest_wrong_format_length_pairs() {
376 assert!(Digest::from_bytes(ObjectFormat::Sha1, &[0u8; 32]).is_err());
377 assert!(Digest::from_bytes(ObjectFormat::Sha256, &[0u8; 20]).is_err());
378 }
379
380 #[test]
381 fn sha1_collision_error_message_names_obj004() {
382 let msg = HashError::Sha1Collision.to_string();
383 assert!(msg.contains("OBJ-004"));
384 assert!(msg.contains("detect+refuse"));
385 assert!(msg.contains("Impossible"));
386 }
387
388 #[test]
398 fn refuses_shattered_pdf_fixture_when_present() {
399 let path =
400 std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/shattered-1.pdf");
401 if !path.is_file() {
402 return;
403 }
404 let bytes = std::fs::read(&path).expect("read shattered fixture");
405 let err = hash_bytes(ObjectFormat::Sha1, &bytes).expect_err("must detect collision");
406 assert_eq!(err, HashError::Sha1Collision);
407 }
408
409 #[test]
410 fn container_hash_matches_standard_sha1_and_sha256_across_boundaries() {
411 for len in [0usize, 1, 3, 55, 56, 57, 63, 64, 65, 127, 128, 129, 65_536] {
412 let data: Vec<u8> = (0..len).map(|i| ((i * 31 + 7) % 251) as u8).collect();
413 assert_eq!(
414 hash_container_bytes(ObjectFormat::Sha1, &data),
415 hash_bytes(ObjectFormat::Sha1, &data).unwrap(),
416 "sha1 mismatch at len={len}"
417 );
418 assert_eq!(
419 hash_container_bytes(ObjectFormat::Sha256, &data),
420 hash_bytes(ObjectFormat::Sha256, &data).unwrap(),
421 "sha256 mismatch at len={len}"
422 );
423 }
424 }
425}
426
427#[cfg(test)]
428mod hex {
429 pub fn encode_lower(bytes: &[u8]) -> String {
430 let mut s = String::with_capacity(bytes.len() * 2);
431 for b in bytes {
432 s.push_str(&format!("{b:02x}"));
433 }
434 s
435 }
436}