diff --git a/util/util.go b/util/util.go new file mode 100644 index 0000000..cddc0d7 --- /dev/null +++ b/util/util.go @@ -0,0 +1,13 @@ +// package util provides small utility functions that make it easier to express common things +package util + +import "encoding/hex" + +// DeHex decodes a hexadecimal string into a byte slice. Panics if the string is invalid. +func DeHex(s string) []byte { + decoded, err := hex.DecodeString(s) + if err != nil { + panic("invalid hex string") + } + return decoded +} diff --git a/util/util_test.go b/util/util_test.go new file mode 100644 index 0000000..2adf416 --- /dev/null +++ b/util/util_test.go @@ -0,0 +1,25 @@ +package util_test + +import ( + "testing" + + "git.omicron.one/playground/cryptography/util" + "github.com/stretchr/testify/assert" +) + +func TestDeHex(t *testing.T) { + b := util.DeHex("") + assert.NotNil(t, b) + assert.Len(t, b, 0) + + b = util.DeHex("deadbeef") + assert.NotNil(t, b) + assert.Equal(t, []byte("\xde\xad\xbe\xef"), b) + + assert.PanicsWithValue(t, "invalid hex string", func() { + util.DeHex("dead serious this is not a hex string") + }) + assert.PanicsWithValue(t, "invalid hex string", func() { + util.DeHex("deada55") + }) +}