feature: added hasher

master
amorozov 2024-06-25 19:18:27 +03:00
parent dd83b872db
commit ac8c18e754
1 changed files with 72 additions and 0 deletions

View File

@ -0,0 +1,72 @@
package hasher
import (
"crypto/md5"
"crypto/sha256"
"hash"
"io"
"os"
)
type Hasher struct {
HashSupplier func() hash.Hash
}
func NewSha256Hasher() *Hasher {
return NewHasher(func() hash.Hash {
return sha256.New()
},
)
}
func NewMd5Hasher() *Hasher {
return NewHasher(func() hash.Hash {
return md5.New()
},
)
}
func NewHasher(hashSupplier func() hash.Hash) *Hasher {
return &Hasher{
HashSupplier: hashSupplier,
}
}
func (self *Hasher) GetFileHashString(fileLocation string) (string, error) {
bytes, err := self.GetFileHashBytes(fileLocation)
if err != nil {
return "", err
}
return string(bytes), nil
}
func (self *Hasher) GetFileHashBytes(fileLocation string) ([]byte, error) {
file, err := os.Open(fileLocation)
if err != nil {
return nil, err
}
defer file.Close()
return self.GetHashBytes(file)
}
func (self *Hasher) GetHashString(reader io.Reader) (string, error) {
bytes, err := self.GetHashBytes(reader)
if err != nil {
return "", err
}
return string(bytes), nil
}
func (self *Hasher) GetHashBytes(reader io.Reader) ([]byte, error) {
hasher := self.HashSupplier()
_, err := io.Copy(hasher, reader)
if err != nil {
return nil, err
}
return hasher.Sum(nil), nil
}