forked from ava-labs/avalanchego
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathverify.go
42 lines (37 loc) · 1.13 KB
/
verify.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
// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package staking
import (
"crypto"
"crypto/ecdsa"
"crypto/rsa"
"errors"
)
var (
ErrUnsupportedAlgorithm = errors.New("staking: cannot verify signature: unsupported algorithm")
ErrECDSAVerificationFailure = errors.New("staking: ECDSA verification failure")
)
// CheckSignature verifies that the signature is a valid signature over signed
// from the certificate.
//
// Ref: https://github.com/golang/go/blob/go1.19.12/src/crypto/x509/x509.go#L793-L797
// Ref: https://github.com/golang/go/blob/go1.19.12/src/crypto/x509/x509.go#L816-L879
func CheckSignature(cert *Certificate, msg []byte, signature []byte) error {
hasher := crypto.SHA256.New()
_, err := hasher.Write(msg)
if err != nil {
return err
}
hashed := hasher.Sum(nil)
switch pub := cert.PublicKey.(type) {
case *rsa.PublicKey:
return rsa.VerifyPKCS1v15(pub, crypto.SHA256, hashed, signature)
case *ecdsa.PublicKey:
if !ecdsa.VerifyASN1(pub, hashed, signature) {
return ErrECDSAVerificationFailure
}
return nil
default:
return ErrUnsupportedAlgorithm
}
}