generated from ZEISS/template-go
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: b64 content hash and hmac sign
- Loading branch information
1 parent
3bdd3c8
commit 75d68bc
Showing
2 changed files
with
72 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} |