Skip to content
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

fix: update the hash generation logic #1676

Open
wants to merge 2 commits into
base: main
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
41 changes: 25 additions & 16 deletions pkg/util/secretutil/secret.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,13 @@ import (
"crypto/x509"
"encoding/pem"
"fmt"
"io"
"os"
"sort"
"strings"

secretsstorev1 "sigs.k8s.io/secrets-store-csi-driver/apis/v1"

"golang.org/x/crypto/cryptobyte"
"golang.org/x/crypto/pkcs12"
corev1 "k8s.io/api/core/v1"
)
Expand Down Expand Up @@ -217,23 +217,32 @@ func GetSecretData(secretObjData []*secretsstorev1.SecretObjectData, secretType

// GetSHAFromSecret gets SHA for the secret data
func GetSHAFromSecret(data map[string][]byte) (string, error) {
var values []string
for k, v := range data {
values = append(values, k+"="+string(v))
}
// sort the values to always obtain a deterministic SHA for
// same content in different order
sort.Strings(values)
return generateSHA(strings.Join(values, ";"))
}
if len(data) == 0 {
return "", nil
}

b := cryptobyte.NewBuilder(nil)
b.AddUint32(uint32(len(data)))

keys := make([]string, 0, len(data))
for k := range data {
keys = append(keys, k)
}
sort.Strings(keys)

for _, k := range keys {
b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
b.AddBytes([]byte(k))
})
b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
b.AddBytes(data[k])
})
}

// generateSHA generates SHA from string
func generateSHA(data string) (string, error) {
hasher := sha256.New()
_, err := io.WriteString(hasher, data)
hashData, err := b.Bytes()
if err != nil {
return "", err
}
sha := hasher.Sum(nil)
return fmt.Sprintf("%x", sha), nil

return fmt.Sprintf("%x", sha256.Sum256(hashData)), nil
}
10 changes: 10 additions & 0 deletions pkg/util/secretutil/secret_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,16 @@ func TestGenerateSHAFromSecret(t *testing.T) {
data2: map[string][]byte{"key2": []byte("value2"), "key1": []byte("value1")},
expectedSHAMatch: true,
},
{
name: "different keys with the same concatenated result but should not match",
data1: map[string][]byte{
"key1": []byte("=value1"),
},
data2: map[string][]byte{
"key1=": []byte("value1"),
},
expectedSHAMatch: false,
},
}

for _, test := range tests {
Expand Down
Loading