From 9469d0f61afbc786ddee0bc778950792f1774052 Mon Sep 17 00:00:00 2001 From: Aneurin Barker Snook Date: Tue, 10 Oct 2023 21:56:47 +0100 Subject: [PATCH] add simple hash functions, tests --- go.mod | 3 +++ hash.go | 27 +++++++++++++++++++++++++++ hash_test.go | 45 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 75 insertions(+) create mode 100644 go.mod create mode 100644 hash.go create mode 100644 hash_test.go diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..f316f36 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/recipeer/go/hash + +go 1.21.2 diff --git a/hash.go b/hash.go new file mode 100644 index 0000000..32f58fa --- /dev/null +++ b/hash.go @@ -0,0 +1,27 @@ +package hash + +import ( + "crypto/sha256" + "crypto/sha512" + "encoding/hex" +) + +// SHA256 creates a hex-encoded SHA256 checksum for a string input. +func SHA256(value string) string { + b := sha256.Sum256([]byte(value)) + hash := []byte{} + for _, byte := range b { + hash = append(hash, byte) + } + return hex.EncodeToString(hash) +} + +// SHA512 creates a hex-encoded SHA512 checksum for a string input. +func SHA512(value string) string { + b := sha512.Sum512([]byte(value)) + hash := []byte{} + for _, byte := range b { + hash = append(hash, byte) + } + return hex.EncodeToString(hash) +} diff --git a/hash_test.go b/hash_test.go new file mode 100644 index 0000000..1671294 --- /dev/null +++ b/hash_test.go @@ -0,0 +1,45 @@ +package hash + +import "testing" + +func TestSHA256(t *testing.T) { + type TestCase struct { + Input string + Output string + } + + testCases := []TestCase{ + {Input: "Gnocchi", Output: "5590208af75dc079e5e500fa39c982449ecbb02010f093a4de8b3377250c6f99"}, + {Input: "Spaghetti", Output: "dd81cff28075d9126e35ce2ba895a3ce95a9ecdc1ac899418ace10e7a697127d"}, + } + + for i, tc := range testCases { + t.Logf("(%d) Testing %q", i, tc.Input) + + out := SHA256(tc.Input) + if out != tc.Output { + t.Errorf("Expected %q, got %q", tc.Output, out) + } + } +} + +func TestSHA512(t *testing.T) { + type TestCase struct { + Input string + Output string + } + + testCases := []TestCase{ + {Input: "Gnocchi", Output: "43d0c2d7ee218cc30221c83e57c4ea3e6a68ce73225aff9b77c148e86f97c0b5d98a018a503115c4a81b9364cf132f5fc42878ece0412346aa60f2ea01f54756"}, + {Input: "Spaghetti", Output: "259f2043005a92915be7bd288050cffdc4f55201c823b5837e22b053ef982e364bf3625ee41c676b91047a450b33e66660ec6346690b234c2a0c47c832043ef2"}, + } + + for i, tc := range testCases { + t.Logf("(%d) Testing %q", i, tc.Input) + + out := SHA512(tc.Input) + if out != tc.Output { + t.Errorf("Expected %q, got %q", tc.Output, out) + } + } +}