From 41a62f783d6751c121710b5249a1b3089613171e Mon Sep 17 00:00:00 2001 From: Christian Uhsat Date: Sat, 18 May 2024 01:42:17 +0200 Subject: [PATCH] version 0.10.2 --- internal/hash/hash.go | 66 ++++++++++++++++++++++++++++++++++++++ internal/hash/hash_test.go | 54 +++++++++++++++++++++++++++++++ 2 files changed, 120 insertions(+) create mode 100644 internal/hash/hash.go create mode 100644 internal/hash/hash_test.go diff --git a/internal/hash/hash.go b/internal/hash/hash.go new file mode 100644 index 0000000..3f0af21 --- /dev/null +++ b/internal/hash/hash.go @@ -0,0 +1,66 @@ +// Hash functions. +package hash + +import ( + "crypto/md5" + "crypto/sha1" + "crypto/sha256" + "errors" + "hash" + "hash/crc32" + "io" + "os" + "strings" +) + +const ( + CRC32 = "crc32" + MD5 = "md5" + SHA1 = "sha1" + SHA256 = "sha256" +) + +var Supported = [...]string{CRC32, MD5, SHA1, SHA256} + +func Sum(name, algo string) (b []byte, err error) { + h, err := new(algo) + + if err != nil { + return + } + + f, err := os.Open(name) + + if err != nil { + return + } + + defer f.Close() + + if _, err = io.Copy(h, f); err != nil { + return + } + + b = h.Sum(nil) + + return +} + +func new(name string) (h hash.Hash, err error) { + switch strings.ToLower(name) { + case CRC32: + h = crc32.NewIEEE() + case MD5: + h = md5.New() + case SHA1: + h = sha1.New() + case SHA256: + h = sha256.New() + default: + if len(name) > 0 { + err = errors.New("algorithms supported: " + strings.Join(Supported[:], " ")) + } + } + + return +} diff --git a/internal/hash/hash_test.go b/internal/hash/hash_test.go new file mode 100644 index 0000000..1cd0122 --- /dev/null +++ b/internal/hash/hash_test.go @@ -0,0 +1,54 @@ +// Hash implementation tests. +package hash + +import ( + "fmt" + "testing" + + "github.com/cuhsat/fact/internal/test" +) + +func TestSum(t *testing.T) { + cases := []struct { + name, file, algo, sum string + }{ + { + name: "Test with crc32", + file: test.Testdata("mbr"), + algo: CRC32, + sum: "14e55a3a", + }, + { + name: "Test with md5", + file: test.Testdata("mbr"), + algo: MD5, + sum: "cb3ca368f5f6514d9a47f3723bddf826", + }, + { + name: "Test with sha1", + file: test.Testdata("mbr"), + algo: SHA1, + sum: "830a4645a04b895eb5e19bfa3eb017423aad9758", + }, + { + name: "Test with sha256", + file: test.Testdata("mbr"), + algo: SHA256, + sum: "f58ca4adc037022d6a00d87f90b9480a580a5af5cac948b28bf7d8e0793107a1", + }, + } + + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + s, err := Sum(tt.file, tt.algo) + + if err != nil { + t.Fatal(err) + } + + if fmt.Sprintf("%x", s) != tt.sum { + t.Fatal("Sum mismatch") + } + }) + } +}