Skip to content

Instantly share code, notes, and snippets.

@jenting
Created March 14, 2022 07:10
Show Gist options
  • Save jenting/dccf1a3d76fb634fb2e64a92600ade46 to your computer and use it in GitHub Desktop.
Save jenting/dccf1a3d76fb634fb2e64a92600ade46 to your computer and use it in GitHub Desktop.
SHA512 checksum
package main
import (
"crypto/sha512"
"encoding/hex"
"flag"
"fmt"
"io"
"os"
"github.com/longhorn/sparse-tools/sparse"
)
func main() {
flag.Parse()
fmt.Printf("Calculate the %q checksum\n", flag.Arg(0))
checksum, err := GetFileChecksum(flag.Arg(0))
fmt.Printf("Checksum: %v, err %v\n", checksum, err)
}
func GetFileChecksum(filePath string) (string, error) {
f, err := sparse.NewDirectFileIoProcessor(filePath, os.O_RDONLY, 0)
if err != nil {
return "", err
}
defer f.Close()
// 4MB
buf := make([]byte, 1<<22)
h := sha512.New()
for {
nr, err := f.Read(buf)
if err != nil {
if err != io.EOF {
return "", err
}
break
}
h.Write(buf[:nr])
}
return hex.EncodeToString(h.Sum(nil)), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment