func GetFileSHA3(fp string) (hexhash string) { if DEBUG { fmt.Printf("GetFileMD5: computing hash for '%s'\n", fp) } h := sha3.NewKeccak224() fd, err := os.Open(fp) if err != nil { fmt.Printf("GetFileMD5: can't get MD5 for %s: %s", fp, err) } defer func() { if err := fd.Close(); err != nil { panic(err) } }() reader := bufio.NewReader(fd) buf := make([]byte, 4096) for { block, err := reader.Read(buf) if err != nil && err != io.EOF { panic(err) } if block == 0 { break } h.Write(buf[:block]) } hexhash = fmt.Sprintf("%x %s", h.Sum(nil), fp) return }
// getHash calculates the hash of a file. // It reads a file block by block, and updates a hashsum with each block. // Reading by blocks consume very little memory, which is needed for large files. // parameters: // - fd is an open file descriptor that points to the file to inspect // - hashType is an integer that define the type of hash // return: // - hexhash, the hex encoded hash of the file found at fp func getHash(fd *os.File, hashType int) (hexhash string) { if DEBUG { fmt.Printf("getHash: computing hash for '%s'\n", fd.Name()) } var h hash.Hash switch hashType { case CheckMD5: h = md5.New() case CheckSHA1: h = sha1.New() case CheckSHA256: h = sha256.New() case CheckSHA384: h = sha512.New384() case CheckSHA512: h = sha512.New() case CheckSHA3_224: h = sha3.NewKeccak224() case CheckSHA3_256: h = sha3.NewKeccak256() case CheckSHA3_384: h = sha3.NewKeccak384() case CheckSHA3_512: h = sha3.NewKeccak512() default: err := fmt.Sprintf("getHash: Unkown hash type %d", hashType) panic(err) } buf := make([]byte, 4096) var offset int64 = 0 for { block, err := fd.ReadAt(buf, offset) if err != nil && err != io.EOF { panic(err) } if block == 0 { break } h.Write(buf[:block]) offset += int64(block) } hexhash = fmt.Sprintf("%x", h.Sum(nil)) return }