Skip to content

Commit

Permalink
fix: update sha generation logic
Browse files Browse the repository at this point in the history
Signed-off-by: Anish Ramasekar <anish.ramasekar@gmail.com>
  • Loading branch information
aramase committed Oct 25, 2024
1 parent b94492d commit aae8991
Showing 1 changed file with 25 additions and 16 deletions.
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
}

0 comments on commit aae8991

Please sign in to comment.