ProofedMesh/services/admin-api/internal/attest/hash.go

94 lines
2.1 KiB
Go
Raw Normal View History

package attest
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"sort"
)
// sha256hex returns the hex-encoded SHA-256 of b.
func sha256hex(b []byte) string {
sum := sha256.Sum256(b)
return hex.EncodeToString(sum[:])
}
// jsonMarshalSortedKeys produces a stable JSON encoding with keys sorted
// recursively in every object. This is the stability we need for hashing;
// it is NOT a full RFC 8785 implementation (no number-canonicalisation,
// no string-escape canonicalisation), but all values we hash are strings,
// nulls, maps, or arrays of those, which stay stable under encoding/json.
func jsonMarshalSortedKeys(v any) ([]byte, error) {
// Round-trip through generic unmarshal to get the canonical shape, then
// emit sorted. For our (small, well-shaped) inputs this is cheap.
first, err := json.Marshal(v)
if err != nil {
return nil, err
}
var any_ any
if err := json.Unmarshal(first, &any_); err != nil {
return nil, err
}
var buf bytes.Buffer
if err := writeSorted(&buf, any_); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func writeSorted(buf *bytes.Buffer, v any) error {
switch x := v.(type) {
case nil:
buf.WriteString("null")
case bool:
if x {
buf.WriteString("true")
} else {
buf.WriteString("false")
}
case float64:
// json.Unmarshal gives floats for all numbers. In our payloads we
// never emit raw numbers; everything is a string.
b, _ := json.Marshal(x)
buf.Write(b)
case string:
b, _ := json.Marshal(x)
buf.Write(b)
case []any:
buf.WriteByte('[')
for i, el := range x {
if i > 0 {
buf.WriteByte(',')
}
if err := writeSorted(buf, el); err != nil {
return err
}
}
buf.WriteByte(']')
case map[string]any:
keys := make([]string, 0, len(x))
for k := range x {
keys = append(keys, k)
}
sort.Strings(keys)
buf.WriteByte('{')
for i, k := range keys {
if i > 0 {
buf.WriteByte(',')
}
kb, _ := json.Marshal(k)
buf.Write(kb)
buf.WriteByte(':')
if err := writeSorted(buf, x[k]); err != nil {
return err
}
}
buf.WriteByte('}')
default:
return fmt.Errorf("writeSorted: unsupported type %T", v)
}
return nil
}