Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changes/20251027111917.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
:sparkles: [hashing] Add helpers to simplify hashing
22 changes: 21 additions & 1 deletion utils/hashing/hash.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
package hashing

import (
"bytes"
"context"
"crypto/md5" //nolint:gosec
"crypto/sha1" //nolint:gosec
Expand Down Expand Up @@ -36,6 +37,10 @@ const (
HashBlake2256 = "blake2b256" // https://www.blake2.net/
)

var (
SupportedHashingAlgorithms = []string{HashMd5, HashXXHash, HashSha1, HashSha256, HashMurmur, HashBlake2256}
)

type hashingAlgo struct {
Hash hash.Hash
Type string
Expand Down Expand Up @@ -133,7 +138,7 @@ func NewHashingAlgorithm(htype string) (IHash, error) {
}

if hash == nil {
return nil, commonerrors.New(commonerrors.ErrNotFound, "could not find the corresponding hashing algorithm")
return nil, commonerrors.Newf(commonerrors.ErrNotFound, "could not find the corresponding hashing algorithm. only %v are supported", SupportedHashingAlgorithms)
}
return newHashingAlgorithm(htype, hash)
}
Expand Down Expand Up @@ -196,6 +201,21 @@ func CalculateHashWithContext(ctx context.Context, text, htype string) string {
return CalculateStringHashWithContext(ctx, hashing, text)
}

// CalculateHashFromReader returns the hash of element coming from a reader.
func CalculateHashFromReader(ctx context.Context, htype string, reader io.Reader) (hash string, err error) {
hashing, err := NewHashingAlgorithm(htype)
if err != nil {
return
}
hash, err = hashing.CalculateWithContext(ctx, reader)
return
}

// CalculateBytesHash returns the hash of a byte array
func CalculateBytesHash(ctx context.Context, htype string, array []byte) (string, error) {
return CalculateHashFromReader(ctx, htype, bytes.NewReader(array))
}

// CalculateHashOfListOfStrings calculates the hash of some text using the requested htype hashing algorithm.
func CalculateHashOfListOfStrings(ctx context.Context, htype string, text ...string) string {
hashing, err := NewHashingAlgorithm(htype)
Expand Down
6 changes: 5 additions & 1 deletion utils/hashing/hash_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,13 @@ func TestMd5(t *testing.T) {
}, {
Input: "CMSIS",
Hash: "c61d595888f85f6d30e99ef6cacfcb7d",
}}
},
}
for _, testCase := range testCases {
assert.Equal(t, testCase.Hash, CalculateMD5Hash(testCase.Input))
hash, err := CalculateBytesHash(context.Background(), HashMd5, []byte(testCase.Input))
require.NoError(t, err)
assert.Equal(t, testCase.Hash, hash)
}
}

Expand Down
Loading