-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathecdsa.go
More file actions
71 lines (66 loc) · 1.69 KB
/
ecdsa.go
File metadata and controls
71 lines (66 loc) · 1.69 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
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, sb := make([]byte, lr), 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)
return append(rb, sb...), 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 opaque error; underlying err (e.g. unknown curve) discarded for consistency
return false, fmt.Errorf("signature verification failed")
}
if len(sig) != lr+ls {
// Return opaque error; specific length mismatch discarded to avoid leaking structure
return false, fmt.Errorf("signature verification failed")
}
r := new(big.Int)
r.SetBytes(sig[0:lr])
s := new(big.Int)
s.SetBytes(sig[lr : lr+ls])
if !ecdsa.Verify(pub, hash, r, s) {
return false, fmt.Errorf("signature verification failed")
}
return true, 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
}