github.com/keybase/client/go@v0.0.0-20240309051027-028f7c731f8b/updater/util/digest.go (about) 1 // Copyright 2015 Keybase, Inc. All rights reserved. Use of 2 // this source code is governed by the included BSD license. 3 4 package util 5 6 import ( 7 "crypto/sha256" 8 "encoding/hex" 9 "fmt" 10 "io" 11 "os" 12 ) 13 14 // CheckDigest returns no error if digest matches file 15 func CheckDigest(digest string, path string, log Log) error { 16 if digest == "" { 17 return fmt.Errorf("Missing digest") 18 } 19 calcDigest, err := DigestForFileAtPath(path) 20 if err != nil { 21 return err 22 } 23 if calcDigest != digest { 24 return fmt.Errorf("Invalid digest: %s != %s (%s)", calcDigest, digest, path) 25 } 26 log.Infof("Verified digest: %s (%s)", digest, path) 27 return nil 28 } 29 30 // DigestForFileAtPath returns a SHA256 digest for file at specified path 31 func DigestForFileAtPath(path string) (string, error) { 32 f, err := os.Open(path) 33 if err != nil { 34 return "", err 35 } 36 defer Close(f) 37 return Digest(f) 38 } 39 40 // Digest returns a SHA256 digest 41 func Digest(r io.Reader) (string, error) { 42 hasher := sha256.New() 43 if _, err := io.Copy(hasher, r); err != nil { 44 return "", err 45 } 46 digest := hex.EncodeToString(hasher.Sum(nil)) 47 return digest, nil 48 }