-
Notifications
You must be signed in to change notification settings - Fork 2
/
ecdsa.go
68 lines (63 loc) · 1.44 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
67
68
package httpsign
import (
"crypto/ecdsa"
"fmt"
"io"
"math/big"
)
// These functions extend the ecdsa package by adding raw, JWS-style signatures
func ecdsaSignRaw(rd io.Reader, priv *ecdsa.PrivateKey, hash []byte) ([]byte, error) {
if priv == nil {
return nil, fmt.Errorf("nil private key")
}
r, s, err := ecdsa.Sign(rd, priv, hash)
if err != nil {
return nil, err
}
curve := priv.PublicKey.Params().Name
lr, ls, err := sigComponentLen(curve)
if err != nil {
return nil, err
}
rb := make([]byte, lr)
sb := make([]byte, ls)
if r.BitLen() > 8*lr || s.BitLen() > 8*ls {
return nil, fmt.Errorf("signature values too long")
}
r.FillBytes(rb)
s.FillBytes(sb)
rb = append(rb, sb...)
return rb, nil
}
func ecdsaVerifyRaw(pub *ecdsa.PublicKey, hash []byte, sig []byte) (bool, error) {
if pub == nil {
return false, fmt.Errorf("nil public key")
}
curve := pub.Params().Name
lr, ls, err := sigComponentLen(curve)
if err != nil {
return false, err
}
if len(sig) != lr+ls {
return false, fmt.Errorf("signature length is %d, expecting %d", len(sig), lr+ls)
}
r := new(big.Int)
r.SetBytes(sig[0:lr])
s := new(big.Int)
s.SetBytes(sig[lr : lr+ls])
return ecdsa.Verify(pub, hash, r, s), nil
}
func sigComponentLen(curve string) (int, int, error) {
var lr, ls int
switch curve {
case "P-256":
lr = 32
ls = 32
case "P-384":
lr = 48
ls = 48
default:
return 0, 0, fmt.Errorf("unknown curve \"%s\"", curve)
}
return lr, ls, nil
}