mirror of
https://github.com/luxfi/staking.git
synced 2026-07-27 03:51:29 +00:00
43 lines
1.1 KiB
Go
43 lines
1.1 KiB
Go
// Copyright (C) 2019-2025, Lux Industries, 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
|
||
|
|
}
|
||
|
|
}
|