Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Add generic function to verify checksum
  • Loading branch information
polldo committed Dec 2, 2021
commit fc20a808ece9a082e043e13e3cfa69c571721d76
27 changes: 18 additions & 9 deletions indexes/download/download.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"bytes"
"crypto"
"encoding/hex"
"errors"
"fmt"
"hash"
"io"
Expand Down Expand Up @@ -153,10 +154,10 @@ func Download(d *downloader.Downloader) error {
return nil
}

// VerifyFileChecksum is taken and adapted from https://github.com/arduino/arduino-cli/blob/59b6277a4d6731a1c1579d43aef6df2a46a771d5/arduino/resources/checksums.go
func VerifyFileChecksum(checksum string, filePath *paths.Path) error {
// VerifyChecksum is taken and adapted from https://github.com/arduino/arduino-cli/blob/59b6277a4d6731a1c1579d43aef6df2a46a771d5/arduino/resources/checksums.go
func VerifyChecksum(checksum string, file io.Reader) error {
if checksum == "" {
return fmt.Errorf("missing checksum for: %s", filePath)
return errors.New("missing checksum")
}
split := strings.SplitN(checksum, ":", 2)
if len(split) != 2 {
Expand All @@ -180,21 +181,29 @@ func VerifyFileChecksum(checksum string, filePath *paths.Path) error {
return fmt.Errorf("unsupported hash algorithm: %s", split[0])
}

file, err := filePath.Open()
if err != nil {
return fmt.Errorf("opening file: %s", err)
}
defer file.Close()
if _, err := io.Copy(algo, file); err != nil {
return fmt.Errorf("computing hash: %s", err)
}
if bytes.Compare(algo.Sum(nil), digest) != 0 {
if !bytes.Equal(algo.Sum(nil), digest) {
return fmt.Errorf("archive hash differs from hash in index")
}

return nil
}

// VerifyFileChecksum checks if the passed checksum matches the passed file checksum
func VerifyFileChecksum(checksum string, filePath *paths.Path) error {
file, err := filePath.Open()
if err != nil {
return fmt.Errorf("opening file: %s", err)
}
defer file.Close()
if err = VerifyChecksum(checksum, file); err != nil {
return fmt.Errorf("verifying checksum of file %s: %w", filePath, err)
}
return nil
}

// VerifyFileSize is taken and adapted from https://github.com/arduino/arduino-cli/blob/59b6277a4d6731a1c1579d43aef6df2a46a771d5/arduino/resources/checksums.go
func VerifyFileSize(size int64, filePath *paths.Path) error {
info, err := filePath.Stat()
Expand Down