How to calculate the checksum of a sha256 file in Go

I need a utility for Windows that calculates the checksum of the sha256 file so that when loading fedora I can check the checksum here: https://fedoraproject.org/static/checksums/Fedora-18-i386-CHECKSUM

The Microsoft utility from http://support.microsoft.com/kb/889768 only runs md5 and sha1.

I don’t want to use other downloadable tools that are not signed and inaccessible from https or from sources that I don’t know about, because it makes no sense to download unsigned code over an unencrypted connection or from an untrusted source to verify the signature of another code to trust it.

Fortunately, Google provides the ability to use https for all downloads, so I can download Go over secure connection and start from now on.

Here is a simple code that does this for a small file, but it is not very good for large files because it is not streaming.

package main import ( "io/ioutil" "crypto/sha256" "os" "log" "encoding/hex" ) func main() { hasher := sha256.New() s, err := ioutil.ReadFile(os.Args[1]) hasher.Write(s) if err != nil { log.Fatal(err) } os.Stdout.WriteString(hex.EncodeToString(hasher.Sum(nil))) } 

How to make it use streams so that it works with any file size.

+6
source share
3 answers

The SHA256 chassis implements the io.Writer interface, so one option would be to use the io.Copy() function to copy data from the corresponding io.Reader in blocks. Something like this should do:

 f, err := os.Open(os.Args[1]) if err != nil { log.Fatal(err) } defer f.Close() if _, err := io.Copy(hasher, f); err != nil { log.Fatal(err) } 
+18
source

crypto / sha256 godoc actually has a snippet that shows how to do this (this is basically the same code as James):

 package main import ( "crypto/sha256" "fmt" "io" "log" "os" ) func main() { f, err := os.Open("file.txt") if err != nil { log.Fatal(err) } defer f.Close() h := sha256.New() if _, err := io.Copy(h, f); err != nil { log.Fatal(err) } fmt.Printf("%x", h.Sum(nil)) } 
+1
source

Full md5sum example:

 func md5sum(filePath string) (result string, err error) { file, err := os.Open(filePath) if err != nil { return } defer file.Close() hash := md5.New() _, err = io.Copy(hash, file) if err != nil { return } result = hex.EncodeToString(hash.Sum(nil)) return } 

EncodeToString does not skip leading 0 bytes, so fmt.Println(hex.EncodeToString([]byte{0x00, 0x00, 0xA, 0xB, 0xC})) gives 00000a0b0c

0
source

All Articles