diff --git a/crypto/secp256r1/publickey.go b/crypto/secp256r1/publickey.go new file mode 100644 index 0000000000..c92afaa1e0 --- /dev/null +++ b/crypto/secp256r1/publickey.go @@ -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, + } +} diff --git a/crypto/secp256r1/verifier.go b/crypto/secp256r1/verifier.go new file mode 100644 index 0000000000..67a0dd787d --- /dev/null +++ b/crypto/secp256r1/verifier.go @@ -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 +}