/
ecdsa.go
66 lines (56 loc) · 1.13 KB
/
ecdsa.go
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 cose
import (
"crypto/ecdsa"
"crypto/elliptic"
"math/big"
)
func parseECDSA(alg int64, m map[int]interface{}) (interface{}, error) {
var curve elliptic.Curve
switch alg {
case -7:
curve = elliptic.P256()
case -35:
curve = elliptic.P384()
case -36:
curve = elliptic.P521()
default:
return nil, ErrUnsupportedAlgorithm
}
rawD, ok := m[-4]
if !ok { // public key if there is no d
return parseECDSAPublicKey(curve, m)
}
// otherwise, we have a private key
dBytes, ok := rawD.([]byte)
if !ok {
return nil, ErrInvalidFormat
}
return &ecdsa.PrivateKey{
D: big.NewInt(0).SetBytes(dBytes),
}, nil
}
func parseECDSAPublicKey(curve elliptic.Curve, m map[int]interface{}) (*ecdsa.PublicKey, error) {
rawX, ok := m[-2]
if !ok {
return nil, ErrInvalidFormat
}
xBytes, ok := rawX.([]byte)
if !ok {
return nil, ErrInvalidFormat
}
rawY, ok := m[-3]
if !ok {
return nil, ErrInvalidFormat
}
yBytes, ok := rawY.([]byte)
if !ok {
return nil, ErrInvalidFormat
}
x := big.NewInt(0).SetBytes(xBytes)
y := big.NewInt(0).SetBytes(yBytes)
return &ecdsa.PublicKey{
Curve: curve,
X: x,
Y: y,
}, nil
}