| 1 |
// Copyright (c) 2014-2019 Ludovic Fauvet |
| 2 |
// Licensed under the MIT license |
| 3 |
|
| 4 |
package filesystem |
| 5 |
|
| 6 |
import ( |
| 7 |
"bufio" |
| 8 |
"crypto/md5" |
| 9 |
"crypto/sha1" |
| 10 |
"crypto/sha256" |
| 11 |
"encoding/hex" |
| 12 |
"hash" |
| 13 |
"io" |
| 14 |
"os" |
| 15 |
|
| 16 |
. "github.com/etix/mirrorbits/config" |
| 17 |
) |
| 18 |
|
| 19 |
// HashFile generates a human readable hash of the given file path |
| 20 |
func HashFile(path string) (hashes FileInfo, err error) { |
| 21 |
f, err := os.Open(path) |
| 22 |
if err != nil { |
| 23 |
return |
| 24 |
} |
| 25 |
defer f.Close() |
| 26 |
|
| 27 |
reader := bufio.NewReader(f) |
| 28 |
|
| 29 |
var writers []io.Writer |
| 30 |
|
| 31 |
if GetConfig().Hashes.SHA1 { |
| 32 |
hsha1 := newHasher(sha1.New(), &hashes.Sha1) |
| 33 |
defer hsha1.Close() |
| 34 |
writers = append(writers, hsha1) |
| 35 |
} |
| 36 |
if GetConfig().Hashes.SHA256 { |
| 37 |
hsha256 := newHasher(sha256.New(), &hashes.Sha256) |
| 38 |
defer hsha256.Close() |
| 39 |
writers = append(writers, hsha256) |
| 40 |
} |
| 41 |
if GetConfig().Hashes.MD5 { |
| 42 |
hmd5 := newHasher(md5.New(), &hashes.Md5) |
| 43 |
defer hmd5.Close() |
| 44 |
writers = append(writers, hmd5) |
| 45 |
} |
| 46 |
|
| 47 |
if len(writers) == 0 { |
| 48 |
return |
| 49 |
} |
| 50 |
|
| 51 |
w := io.MultiWriter(writers...) |
| 52 |
|
| 53 |
_, err = io.Copy(w, reader) |
| 54 |
if err != nil { |
| 55 |
return |
| 56 |
} |
| 57 |
|
| 58 |
return |
| 59 |
} |
| 60 |
|
| 61 |
type hasher struct { |
| 62 |
hash.Hash |
| 63 |
output *string |
| 64 |
} |
| 65 |
|
| 66 |
func newHasher(hash hash.Hash, output *string) hasher { |
| 67 |
return hasher{ |
| 68 |
Hash: hash, |
| 69 |
output: output, |
| 70 |
} |
| 71 |
} |
| 72 |
|
| 73 |
func (h hasher) Close() error { |
| 74 |
*h.output = hex.EncodeToString(h.Sum(nil)) |
| 75 |
return nil |
| 76 |
} |
| 77 |
|
| 78 |
// Sha256sum generates a human readable sha256 hash of the given file path |
| 79 |
func Sha256sum(path string) ([]byte, error) { |
| 80 |
f, err := os.Open(path) |
| 81 |
if err != nil { |
| 82 |
return nil, err |
| 83 |
} |
| 84 |
defer f.Close() |
| 85 |
|
| 86 |
h := sha256.New() |
| 87 |
if _, err := io.Copy(h, f); err != nil { |
| 88 |
return nil, err |
| 89 |
} |
| 90 |
|
| 91 |
return h.Sum(nil), nil |
| 92 |
} |