Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
9 changes: 6 additions & 3 deletions pkg/files/file_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@ package files

import (
"cmp"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"fmt"
"net"
"os"
"slices"
"strconv"

"github.com/google/uuid"

mpi "github.com/nginx/agent/v3/api/grpc/mpi/v1"
"github.com/nginx/agent/v3/internal/datasource/cert"
"google.golang.org/protobuf/types/known/timestamppb"
Expand Down Expand Up @@ -135,7 +135,10 @@ func GenerateConfigVersion(fileSlice []*mpi.File) string {

// GenerateHash returns the hash value of a file's contents.
func GenerateHash(b []byte) string {
return uuid.NewMD5(uuid.Nil, b).String()
hash := sha256.New()
hash.Write(b)

return base64.StdEncoding.EncodeToString(hash.Sum(nil))
}

// ConvertToMapOfFiles converts a list of files to a map of files with the file name as the key
Expand Down
11 changes: 8 additions & 3 deletions pkg/files/file_helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@
package files

import (
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"net"
"os"
"testing"

"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

Expand Down Expand Up @@ -136,6 +137,10 @@ func Test_GenerateConfigVersion(t *testing.T) {
}

func TestGenerateHash(t *testing.T) {
hash1 := sha256.New()
hash2 := sha256.New()
hash1.Write([]byte(""))
hash2.Write([]byte("test"))
tests := []struct {
name string
expected string
Expand All @@ -144,12 +149,12 @@ func TestGenerateHash(t *testing.T) {
{
name: "Test 1: empty byte slice",
input: []byte{},
expected: uuid.NewMD5(uuid.Nil, []byte("")).String(),
expected: base64.StdEncoding.EncodeToString(hash1.Sum(nil)),
},
{
name: "Test 2: non-empty byte slice",
input: []byte("test"),
expected: uuid.NewMD5(uuid.Nil, []byte("test")).String(),
expected: base64.StdEncoding.EncodeToString(hash2.Sum(nil)),
},
}

Expand Down