linsk/storage/hash.go

48 lines
822 B
Go
Raw Normal View History

2023-08-30 12:39:38 +01:00
package storage
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"os"
2023-09-02 12:14:02 +01:00
"path/filepath"
2023-08-30 12:39:38 +01:00
"github.com/pkg/errors"
)
func validateFileHash(path string, hash []byte) error {
2023-09-02 12:14:02 +01:00
pathClean := filepath.Clean(path)
f, err := os.OpenFile(pathClean, os.O_RDONLY, 0400)
2023-08-30 12:39:38 +01:00
if err != nil {
return errors.Wrap(err, "open file")
}
defer func() { _ = f.Close() }()
h := sha256.New()
block := make([]byte, 1024)
for {
read, err := f.Read(block)
if read > 0 {
h.Write(block[:read])
}
if err != nil {
if errors.Is(err, io.EOF) {
break
}
return errors.Wrap(err, "read file block")
}
}
sum := h.Sum(nil)
if !bytes.Equal(sum, hash) {
2023-09-02 12:14:02 +01:00
return fmt.Errorf("hash mismatch: want '%v', have '%v' (path '%v')", hex.EncodeToString(hash), hex.EncodeToString(sum), pathClean)
2023-08-30 12:39:38 +01:00
}
return nil
}