Skip to content

Change hash generation #1045

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: v3
Choose a base branch
from
Open
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))

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the reason for encoding the hash value in Base64?

}

// 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 @@ -139,6 +140,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 @@ -147,12 +152,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