github.com/josephvusich/fdf@v0.0.0-20230522095411-9326dd32e33f/checksum.go (about) 1 package main 2 3 import ( 4 "crypto/rand" 5 "fmt" 6 "io" 7 8 "github.com/minio/highwayhash" 9 ) 10 11 const ChecksumBlockSize = 16 12 13 // 32 bytes of random hash key 14 var hashKey []byte 15 16 func init() { 17 hashKey = make([]byte, 32) 18 rand.Read(hashKey) 19 20 h, err := highwayhash.New128(hashKey) 21 if err != nil { 22 panic(err) 23 } 24 25 if h.Size() != ChecksumBlockSize { 26 panic("unexpected block size") 27 } 28 } 29 30 // updateDB is false if the file being checksummed has not yet been added to the DB 31 func (t *fileTable) Checksum(r *fileRecord, updateDB bool) error { 32 if r.HasChecksum { 33 return nil 34 } 35 36 if r.FailedChecksum != nil { 37 return r.FailedChecksum 38 } 39 40 t.progress(r.RelPath, false) 41 42 f, err := t.options.OpenFile(r.FilePath) 43 if err != nil { 44 r.FailedChecksum = err 45 t.totals.Errors.Add(r) 46 fmt.Printf("%s: %s\n", r.RelPath, err) 47 return err 48 } 49 defer f.Close() 50 51 b, err := hwhChecksum(f) 52 if err != nil { 53 r.FailedChecksum = err 54 t.totals.Errors.Add(r) 55 fmt.Printf("%s: %s\n", r.RelPath, err) 56 return err 57 } 58 59 r.Checksum.size = r.Size() 60 copy(r.Checksum.hash[:], b) 61 r.HasChecksum = true 62 63 if updateDB { 64 // Update indexes with new checksum 65 t.db.insert(r) 66 } 67 return nil 68 } 69 70 func hwhChecksum(r io.Reader) ([]byte, error) { 71 h, err := highwayhash.New128(hashKey) 72 if err != nil { 73 return nil, err 74 } 75 76 _, err = io.Copy(h, r) 77 if err != nil { 78 return nil, err 79 } 80 81 return h.Sum(nil), nil 82 }