forked from MicahParks/keyfunc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathecdsa.go
More file actions
91 lines (72 loc) · 2.23 KB
/
Copy pathecdsa.go
File metadata and controls
91 lines (72 loc) · 2.23 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package keyfunc
import (
"crypto/ecdsa"
"crypto/elliptic"
"encoding/base64"
"fmt"
"math/big"
)
const (
// es256 represents a public cryptography key generated by a 256 bit ECDSA algorithm.
es256 = "ES256"
// es384 represents a public cryptography key generated by a 384 bit ECDSA algorithm.
es384 = "ES384"
// es512 represents a public cryptography key generated by a 512 bit ECDSA algorithm.
es512 = "ES512"
// p256 represents a cryptographic elliptical curve type.
p256 = "P-256"
// p384 represents a cryptographic elliptical curve type.
p384 = "P-384"
// p521 represents a cryptographic elliptical curve type.
p521 = "P-521"
)
// ECDSA parses a JSONKey and turns it into an ECDSA public key.
func (j *JSONKey) ECDSA() (publicKey *ecdsa.PublicKey, err error) {
// Check if the key has already been computed.
if j.precomputed != nil {
var ok bool
if publicKey, ok = j.precomputed.(*ecdsa.PublicKey); ok {
return publicKey, nil
}
}
// Confirm everything needed is present.
if j.X == "" || j.Y == "" || j.Curve == "" {
return nil, fmt.Errorf("%w: ecdsa", ErrMissingAssets)
}
// Decode the X coordinate from Base64.
//
// According to RFC 7518, this is a Base64 URL unsigned integer.
// https://tools.ietf.org/html/rfc7518#section-6.3
var xCoordinate []byte
if xCoordinate, err = base64.RawURLEncoding.DecodeString(j.X); err != nil {
return nil, err
}
// Decode the Y coordinate from Base64.
var yCoordinate []byte
if yCoordinate, err = base64.RawURLEncoding.DecodeString(j.Y); err != nil {
return nil, err
}
// Create the ECDSA public key.
publicKey = &ecdsa.PublicKey{}
// Set the curve type.
var curve elliptic.Curve
switch j.Curve {
case p256:
curve = elliptic.P256()
case p384:
curve = elliptic.P384()
case p521:
curve = elliptic.P521()
}
publicKey.Curve = curve
// Turn the X coordinate into *big.Int.
//
// According to RFC 7517, these numbers are in big-endian format.
// https://tools.ietf.org/html/rfc7517#appendix-A.1
publicKey.X = big.NewInt(0).SetBytes(xCoordinate)
// Turn the Y coordinate into a *big.Int.
publicKey.Y = big.NewInt(0).SetBytes(yCoordinate)
// Keep the public key so it won't have to be computed every time.
j.precomputed = publicKey
return publicKey, nil
}