2020-01-12 14:00:56 +01:00
|
|
|
package fs
|
2018-11-17 06:21:39 +01:00
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/sha1"
|
|
|
|
"encoding/hex"
|
2020-02-01 20:52:28 +01:00
|
|
|
"hash/crc32"
|
2018-11-17 06:21:39 +01:00
|
|
|
"io"
|
|
|
|
"os"
|
|
|
|
)
|
|
|
|
|
2020-02-01 20:52:28 +01:00
|
|
|
// Hash returns the SHA1 hash of a file as string.
|
2020-06-29 11:10:24 +02:00
|
|
|
func Hash(fileName string) string {
|
2018-11-17 06:21:39 +01:00
|
|
|
var result []byte
|
|
|
|
|
2020-06-29 11:10:24 +02:00
|
|
|
file, err := os.Open(fileName)
|
2018-11-17 06:21:39 +01:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
|
|
|
defer file.Close()
|
|
|
|
|
|
|
|
hash := sha1.New()
|
|
|
|
|
|
|
|
if _, err := io.Copy(hash, file); err != nil {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
|
|
|
return hex.EncodeToString(hash.Sum(result))
|
2018-11-17 06:56:43 +01:00
|
|
|
}
|
2020-02-01 20:52:28 +01:00
|
|
|
|
|
|
|
// Checksum returns the CRC32 checksum of a file as string.
|
2020-06-29 11:10:24 +02:00
|
|
|
func Checksum(fileName string) string {
|
2020-02-01 20:52:28 +01:00
|
|
|
var result []byte
|
|
|
|
|
2020-06-29 11:10:24 +02:00
|
|
|
file, err := os.Open(fileName)
|
2020-02-01 20:52:28 +01:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
|
|
|
defer file.Close()
|
|
|
|
|
|
|
|
hash := crc32.New(crc32.MakeTable(crc32.Castagnoli))
|
|
|
|
|
|
|
|
if _, err := io.Copy(hash, file); err != nil {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
|
|
|
return hex.EncodeToString(hash.Sum(result))
|
|
|
|
}
|
2020-06-29 11:10:24 +02:00
|
|
|
|
|
|
|
// IsHash tests if a string looks like a hash.
|
|
|
|
func IsHash(s string) bool {
|
|
|
|
if s == "" {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, r := range s {
|
|
|
|
if (r < 48 || r > 57) && (r < 97 || r > 102) && (r < 65 || r > 70) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
switch len(s) {
|
|
|
|
case 8, 16, 32, 40, 56, 64, 80, 128, 256:
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
return false
|
|
|
|
}
|