github.com/Benchkram/bob@v0.0.0-20220321080157-7c8f3876e225/pkg/filehash/hash.go (about) 1 package filehash 2 3 import ( 4 "crypto/sha1" 5 "fmt" 6 "io" 7 "os" 8 ) 9 10 var ( 11 // Using sha1 shouldn't be a problem as hash collisions are very unlikely. 12 // sha1 is about twice as fast as sha256 on my — Leon's — machine. 13 hashFunc = sha1.New 14 ) 15 16 func Hash(file string) ([]byte, error) { 17 f, err := os.Open(file) 18 if err != nil { 19 return nil, fmt.Errorf("failed to open: %w", err) 20 } 21 defer f.Close() 22 23 return HashBytes(io.Reader(f)) 24 } 25 26 func HashBytes(r io.Reader) ([]byte, error) { 27 h := hashFunc() 28 if _, err := io.Copy(h, r); err != nil { 29 return nil, fmt.Errorf("failed to copy: %w", err) 30 } 31 32 return h.Sum(nil), nil 33 }