github.com/MetalBlockchain/metalgo@v1.11.9/staking/verify.go (about)

     1  // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
     2  // See the file LICENSE for licensing terms.
     3  
     4  package staking
     5  
     6  import (
     7  	"crypto"
     8  	"crypto/ecdsa"
     9  	"crypto/rsa"
    10  	"errors"
    11  )
    12  
    13  var (
    14  	ErrUnsupportedAlgorithm     = errors.New("staking: cannot verify signature: unsupported algorithm")
    15  	ErrECDSAVerificationFailure = errors.New("staking: ECDSA verification failure")
    16  )
    17  
    18  // CheckSignature verifies that the signature is a valid signature over signed
    19  // from the certificate.
    20  //
    21  // Ref: https://github.com/golang/go/blob/go1.19.12/src/crypto/x509/x509.go#L793-L797
    22  // Ref: https://github.com/golang/go/blob/go1.19.12/src/crypto/x509/x509.go#L816-L879
    23  func CheckSignature(cert *Certificate, msg []byte, signature []byte) error {
    24  	hasher := crypto.SHA256.New()
    25  	_, err := hasher.Write(msg)
    26  	if err != nil {
    27  		return err
    28  	}
    29  	hashed := hasher.Sum(nil)
    30  
    31  	switch pub := cert.PublicKey.(type) {
    32  	case *rsa.PublicKey:
    33  		return rsa.VerifyPKCS1v15(pub, crypto.SHA256, hashed, signature)
    34  	case *ecdsa.PublicKey:
    35  		if !ecdsa.VerifyASN1(pub, hashed, signature) {
    36  			return ErrECDSAVerificationFailure
    37  		}
    38  		return nil
    39  	default:
    40  		return ErrUnsupportedAlgorithm
    41  	}
    42  }