-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalgorithm.go
More file actions
66 lines (58 loc) · 1.89 KB
/
Copy pathalgorithm.go
File metadata and controls
66 lines (58 loc) · 1.89 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package rtu
import (
"crypto/sha256"
"fmt"
"github.com/lestrrat-go/jwx/v3/jwa"
)
type SignatureAlgorithm string
// ParseJwa takes a jwa.SignatureAlgorithm and parses a SignatureAlgorithm. (example "ES256" -> "ecdsa-p256")
func ParseJwa(alg jwa.SignatureAlgorithm) (SignatureAlgorithm, error) {
switch alg {
case jwa.EmptySignatureAlgorithm():
return AlgorithmNone, nil
case jwa.ES256():
return AlgorithmEcdsaP256, nil
default:
return AlgorithmNone, fmt.Errorf("%w: unknown jwa algorithm: %s", ErrUnknownSignatureAlgorithm, alg)
}
}
const (
// AlgorithmNone is used when there is no algorithm given in the RTU
AlgorithmNone SignatureAlgorithm = ""
// AlgorithmEcdsaP256 is the signature algorithm for ECDSA with P-256 curve, signing a SHA256 hash.
AlgorithmEcdsaP256 SignatureAlgorithm = "ecdsa-p256"
)
// Digest returns the hash version of payload based on the SignatureAlgorithm given.
// if returned value is nil, it should be treated the same as an ErrSignatureAlgorithmInvalid.
func (s SignatureAlgorithm) Digest(payload []byte) []byte {
switch s {
case AlgorithmEcdsaP256:
hash := sha256.New()
hash.Write(payload)
return hash.Sum(nil)
default:
return nil
}
}
// Validate validates the SignatureAlgorithm, to ensure this library supports it fully
func (s SignatureAlgorithm) Validate() error {
switch s {
case AlgorithmNone:
return ErrNoSignatureAlgorithm
case AlgorithmEcdsaP256:
return nil
default:
return fmt.Errorf("%w: %s", ErrUnknownSignatureAlgorithm, s)
}
}
// ToJWA returns the JSON Web Token Algorithm string for the given SignatureAlgorithm
func (s SignatureAlgorithm) ToJWA() (jwa.SignatureAlgorithm, error) {
switch s {
case AlgorithmNone:
return jwa.EmptySignatureAlgorithm(), ErrNoSignatureAlgorithm
case AlgorithmEcdsaP256:
return jwa.ES256(), nil
default:
return jwa.EmptySignatureAlgorithm(), fmt.Errorf("%w: %s", ErrUnknownSignatureAlgorithm, s)
}
}