forked from inconshreveable/go-update
-
Notifications
You must be signed in to change notification settings - Fork 0
/
verifier.go
74 lines (66 loc) · 2.08 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
64
65
66
67
68
69
70
71
72
73
74
package update
import (
"crypto"
"crypto/dsa"
"crypto/ecdsa"
"crypto/rsa"
"encoding/asn1"
"errors"
"math/big"
)
// Verifier defines an interface for verfiying an update's signature with a public key.
type Verifier interface {
VerifySignature(checksum, signature []byte, h crypto.Hash, publicKey crypto.PublicKey) error
}
type verifyFn func([]byte, []byte, crypto.Hash, crypto.PublicKey) error
func (fn verifyFn) VerifySignature(checksum []byte, signature []byte, hash crypto.Hash, publicKey crypto.PublicKey) error {
return fn(checksum, signature, hash, publicKey)
}
// NewRSAVerifier returns a Verifier that uses the RSA algorithm to verify updates.
func NewRSAVerifier() Verifier {
return verifyFn(func(checksum, signature []byte, hash crypto.Hash, publicKey crypto.PublicKey) error {
key, ok := publicKey.(*rsa.PublicKey)
if !ok {
return errors.New("not a valid RSA public key")
}
return rsa.VerifyPKCS1v15(key, hash, checksum, signature)
})
}
type rsDER struct {
R *big.Int
S *big.Int
}
// NewECDSAVerifier returns a Verifier that uses the ECDSA algorithm to verify updates.
func NewECDSAVerifier() Verifier {
return verifyFn(func(checksum, signature []byte, hash crypto.Hash, publicKey crypto.PublicKey) error {
key, ok := publicKey.(*ecdsa.PublicKey)
if !ok {
return errors.New("not a valid ECDSA public key")
}
var rs rsDER
if _, err := asn1.Unmarshal(signature, &rs); err != nil {
return err
}
if !ecdsa.Verify(key, checksum, rs.R, rs.S) {
return errors.New("failed to verify ecsda signature")
}
return nil
})
}
// NewDSAVerifier returns a Verifier that uses the DSA algorithm to verify updates.
func NewDSAVerifier() Verifier {
return verifyFn(func(checksum, signature []byte, hash crypto.Hash, publicKey crypto.PublicKey) error {
key, ok := publicKey.(*dsa.PublicKey)
if !ok {
return errors.New("not a valid DSA public key")
}
var rs rsDER
if _, err := asn1.Unmarshal(signature, &rs); err != nil {
return err
}
if !dsa.Verify(key, checksum, rs.R, rs.S) {
return errors.New("failed to verify ecsda signature")
}
return nil
})
}