Skip to content

Instantly share code, notes, and snippets.

@hdashk
Last active May 28, 2023 15:05
Show Gist options
  • Save hdashk/c494984ac65110b438beb9545be2970e to your computer and use it in GitHub Desktop.
Save hdashk/c494984ac65110b438beb9545be2970e to your computer and use it in GitHub Desktop.
Method to recursively hash a directory.
package main
import (
"crypto/md5"
"encoding/hex"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"sort"
)
// hashByte calculates the md5 hash of a byte slice and returns it as a string.
func hashByte(contentPtr *[]byte) string {
hasher := md5.New()
hasher.Write(*contentPtr)
return hex.EncodeToString(hasher.Sum(nil))
}
// hashDir hashes all files in a directory recursively.
// The function hashes the file path and content, and then hashes those hashes together.
func hashDir(dir *string) (string, error) {
var finHash string = *dir
var paths []string
err := filepath.Walk(*dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
paths = append(paths, path)
}
return nil
})
if err != nil {
return "", err
}
sort.Strings(paths)
for _, path := range paths {
concatBytes := hashByte(&[]byte{byte(finHash)})
nameHash := hashByte(&[]byte(path))
fileBytes, err := ioutil.ReadFile(path)
if err != nil {
return "", err
}
fileHash := hashByte(&fileBytes)
finHash = concatBytes + fileHash + nameHash
}
return hashByte(&[]byte(finHash)), nil
}
func main() {
dir := "Desktop"
hash, err := hashDir(&dir)
if err != nil {
log.Fatal(err)
}
fmt.Println(hash)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment