...
1 package keyfunc
2
3 import (
4 "crypto/ecdsa"
5 "crypto/elliptic"
6 "errors"
7 "fmt"
8 "math/big"
9 )
10
11 const (
12
13 ktyEC = "EC"
14
15
16 p256 = "P-256"
17
18
19 p384 = "P-384"
20
21
22 p521 = "P-521"
23 )
24
25 var (
26
27 ErrECDSACurve = errors.New("invalid ECDSA curve")
28 )
29
30
31 func (j *jsonWebKey) ECDSA() (publicKey *ecdsa.PublicKey, err error) {
32 if j.X == "" || j.Y == "" || j.Curve == "" {
33 return nil, fmt.Errorf("%w: %s", ErrMissingAssets, ktyEC)
34 }
35
36
37
38
39
40 xCoordinate, err := base64urlTrailingPadding(j.X)
41 if err != nil {
42 return nil, err
43 }
44 yCoordinate, err := base64urlTrailingPadding(j.Y)
45 if err != nil {
46 return nil, err
47 }
48
49 publicKey = &ecdsa.PublicKey{}
50 switch j.Curve {
51 case p256:
52 publicKey.Curve = elliptic.P256()
53 case p384:
54 publicKey.Curve = elliptic.P384()
55 case p521:
56 publicKey.Curve = elliptic.P521()
57 default:
58 return nil, fmt.Errorf("%w: unknown curve: %s", ErrECDSACurve, j.Curve)
59 }
60
61
62
63
64
65 publicKey.X = big.NewInt(0).SetBytes(xCoordinate)
66 publicKey.Y = big.NewInt(0).SetBytes(yCoordinate)
67
68 return publicKey, nil
69 }
70
View as plain text