incredible-go-core/pkg/io/crypto/hasher/hasher.go

78 lines
1.3 KiB
Go

package hasher
import (
"crypto/md5"
"crypto/sha256"
"encoding/hex"
"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 convertBytesToString(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 convertBytesToString(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
}
func convertBytesToString(bytes []byte) string {
return hex.EncodeToString(bytes)
}