crypto/secp2561r1: add secp256r1 curve verifiers
This commit is contained in:
parent
ac3418def6
commit
fb89b61cdc
|
@ -0,0 +1,21 @@
|
|||
package secp256r1
|
||||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"math/big"
|
||||
)
|
||||
|
||||
// Generates approptiate public key format from given coordinates
|
||||
func newPublicKey(x, y *big.Int) *ecdsa.PublicKey {
|
||||
// Check if the given coordinates are valid
|
||||
if x == nil || y == nil || !elliptic.P256().IsOnCurve(x, y) {
|
||||
return nil
|
||||
}
|
||||
|
||||
return &ecdsa.PublicKey{
|
||||
Curve: elliptic.P256(),
|
||||
X: x,
|
||||
Y: y,
|
||||
}
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
package secp256r1
|
||||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"errors"
|
||||
"math/big"
|
||||
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
)
|
||||
|
||||
var (
|
||||
secp256k1halfN = new(big.Int).Div(elliptic.P256().Params().N, big.NewInt(2))
|
||||
)
|
||||
|
||||
// Verifies the given signature (r, s) for the given hash and public key (x, y).
|
||||
func Verify(hash []byte, r, s, x, y *big.Int) ([]byte, error) {
|
||||
// Create the public key format
|
||||
publicKey := newPublicKey(x, y)
|
||||
if publicKey == nil {
|
||||
return nil, errors.New("invalid public key coordinates")
|
||||
}
|
||||
|
||||
if checkMalleability(s) {
|
||||
return nil, errors.New("malleability issue")
|
||||
}
|
||||
|
||||
// Verify the signature with the public key and return 1 if it's valid, 0 otherwise
|
||||
if ok := ecdsa.Verify(publicKey, hash, r, s); ok {
|
||||
return common.LeftPadBytes(common.Big1.Bytes(), 32), nil
|
||||
}
|
||||
|
||||
return common.LeftPadBytes(common.Big0.Bytes(), 32), nil
|
||||
}
|
||||
|
||||
// Check the malleability issue
|
||||
func checkMalleability(s *big.Int) bool {
|
||||
return s.Cmp(secp256k1halfN) <= 0
|
||||
}
|
Loading…
Reference in New Issue