-
Notifications
You must be signed in to change notification settings - Fork 62
/
verifier.go
63 lines (48 loc) · 1.17 KB
/
verifier.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
package ecc
import (
"bytes"
"crypto/ecdsa"
"github.com/dobyte/due/errors"
"math/big"
)
type Verifier struct {
err error
opts *verifierOption
publicKey *ecdsa.PublicKey
}
var DefaultVerifier = NewVerifier()
func NewVerifier(opts ...VerifierOption) *Verifier {
o := defaultVerifierOptions()
for _, opt := range opts {
opt(o)
}
d := &Verifier{opts: o}
d.publicKey, d.err = parseECDSAPublicKey(d.opts.publicKey)
return d
}
// Name 名称
func (v *Verifier) Name() string {
return Name
}
// Verify 验签
func (v *Verifier) Verify(data []byte, signature []byte) (bool, error) {
delimiter := []byte(v.opts.delimiter)
segments := bytes.Split(signature, delimiter)
if len(segments) != 2 {
return false, errors.New("invalid signature")
}
rs := new(big.Int)
ss := new(big.Int)
if err := rs.UnmarshalText(segments[0]); err != nil {
return false, err
}
if err := ss.UnmarshalText(segments[1]); err != nil {
return false, err
}
hashed := v.opts.hash.Sum(data)
return ecdsa.Verify(v.publicKey, hashed[:], rs, ss), nil
}
// Verify 验签
func Verify(data []byte, signature []byte) (bool, error) {
return DefaultVerifier.Verify(data, signature)
}