-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdigest.go
More file actions
43 lines (40 loc) · 1.13 KB
/
digest.go
File metadata and controls
43 lines (40 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package mppx
import (
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
)
// ComputeDigest computes a SHA-256 digest of the given data.
// The returned string is in the format "sha-256=<base64>", suitable for the
// digest field in a Challenge.
//
// data may be a []byte, string, or a JSON-serializable value.
func ComputeDigest(data any) (string, error) {
var raw []byte
switch v := data.(type) {
case []byte:
raw = v
case string:
raw = []byte(v)
default:
b, err := json.Marshal(v)
if err != nil {
return "", fmt.Errorf("mpp: cannot serialize digest input: %w", err)
}
raw = b
}
sum := sha256.Sum256(raw)
return "sha-256=" + base64.StdEncoding.EncodeToString(sum[:]), nil
}
// VerifyDigest verifies that a digest string matches the given data.
// digest must be in the format "sha-256=<base64>".
func VerifyDigest(digest string, data any) (bool, error) {
expected, err := ComputeDigest(data)
if err != nil {
return false, err
}
// Use length-independent comparison to avoid leaking length information,
// though timing-safe comparison of the full strings is sufficient here.
return digest == expected, nil
}