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

78 lines
1.3 KiB
Go
Raw Normal View History

2024-06-25 18:18:27 +02:00
package hasher
import (
"crypto/md5"
"crypto/sha256"
2024-06-25 18:25:04 +02:00
"encoding/hex"
2024-06-25 18:18:27 +02:00
"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
}
2024-06-25 18:25:04 +02:00
return convertBytesToString(bytes), nil
2024-06-25 18:18:27 +02:00
}
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
}
2024-06-25 18:25:04 +02:00
return convertBytesToString(bytes), nil
2024-06-25 18:18:27 +02:00
}
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
}
2024-06-25 18:25:04 +02:00
func convertBytesToString(bytes []byte) string {
return hex.EncodeToString(bytes)
}