Skip to content

Commit

Permalink
version 0.10.2
Browse files Browse the repository at this point in the history
  • Loading branch information
cuhsat committed May 17, 2024
1 parent bdea31b commit 41a62f7
Show file tree
Hide file tree
Showing 2 changed files with 120 additions and 0 deletions.
66 changes: 66 additions & 0 deletions internal/hash/hash.go
Original file line number Diff line number Diff line change
@@ -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
}
54 changes: 54 additions & 0 deletions internal/hash/hash_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
})
}
}

0 comments on commit 41a62f7

Please sign in to comment.