Skip to content

Commit

Permalink
feat: b64 content hash and hmac sign
Browse files Browse the repository at this point in the history
  • Loading branch information
katallaxie authored Oct 10, 2024
1 parent 3bdd3c8 commit 75d68bc
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
42 changes: 42 additions & 0 deletions b64/hmac.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package b64

import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
)

// ContentHash computes the base64 encoded SHA-256 hash of the given content.
func ContentHash(content []byte) (string, error) {
sha256 := sha256.New()

_, err := sha256.Write(content)
if err != nil {
return "", err
}

hb := sha256.Sum(nil)
s := base64.StdEncoding.EncodeToString(hb)

return s, nil
}

// Hmac256 computes the base64 encoded HMAC-SHA-256 hash of the given message using the given secret.
func Hmac256(message, secret string) (string, error) {
decodedSecret, err := base64.StdEncoding.DecodeString(secret)
if err != nil {
return "", err
}

hash := hmac.New(sha256.New, decodedSecret)

_, err = hash.Write([]byte(message))
if err != nil {
return "", err
}

hb := hash.Sum(nil)
s := base64.StdEncoding.EncodeToString(hb)

return s, nil
}
30 changes: 30 additions & 0 deletions b64/hmac_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package b64_test

import (
"testing"

"github.com/zeiss/pkg/b64"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestContentHash(t *testing.T) {
t.Parallel()

content := []byte("test content")
hash, err := b64.ContentHash(content)
require.NoError(t, err)
assert.Equal(t, "auinVVUgn9bEQVfArtgBbnY/9DWhnPGG92hjFAFD/3I=", hash)
}

func TestHmac256(t *testing.T) {
t.Parallel()

message := "test message"
secret := "c2VjcmV0"

hash, err := b64.Hmac256(message, secret)
require.NoError(t, err)
assert.Equal(t, "O86/Q8hdILum47a6J4rx0ro6sNV94nGwrTC4M+hRxaY=", hash)
}

0 comments on commit 75d68bc

Please sign in to comment.