github.com/ethereum/go-ethereum@v1.16.1/crypto/signature_nocgo.go (about)

     1  // Copyright 2017 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  //go:build nacl || js || wasip1 || !cgo || gofuzz || tinygo
    18  // +build nacl js wasip1 !cgo gofuzz tinygo
    19  
    20  package crypto
    21  
    22  import (
    23  	"crypto/ecdsa"
    24  	"errors"
    25  	"fmt"
    26  	"math/big"
    27  
    28  	"github.com/decred/dcrd/dcrec/secp256k1/v4"
    29  	decred_ecdsa "github.com/decred/dcrd/dcrec/secp256k1/v4/ecdsa"
    30  )
    31  
    32  // Ecrecover returns the uncompressed public key that created the given signature.
    33  func Ecrecover(hash, sig []byte) ([]byte, error) {
    34  	pub, err := sigToPub(hash, sig)
    35  	if err != nil {
    36  		return nil, err
    37  	}
    38  	bytes := pub.SerializeUncompressed()
    39  	return bytes, err
    40  }
    41  
    42  func sigToPub(hash, sig []byte) (*secp256k1.PublicKey, error) {
    43  	if len(sig) != SignatureLength {
    44  		return nil, errors.New("invalid signature")
    45  	}
    46  	// Convert to secp256k1 input format with 'recovery id' v at the beginning.
    47  	btcsig := make([]byte, SignatureLength)
    48  	btcsig[0] = sig[RecoveryIDOffset] + 27
    49  	copy(btcsig[1:], sig)
    50  
    51  	pub, _, err := decred_ecdsa.RecoverCompact(btcsig, hash)
    52  	return pub, err
    53  }
    54  
    55  // SigToPub returns the public key that created the given signature.
    56  func SigToPub(hash, sig []byte) (*ecdsa.PublicKey, error) {
    57  	pub, err := sigToPub(hash, sig)
    58  	if err != nil {
    59  		return nil, err
    60  	}
    61  	// We need to explicitly set the curve here, because we're wrapping
    62  	// the original curve to add (un-)marshalling
    63  	return &ecdsa.PublicKey{
    64  		Curve: S256(),
    65  		X:     pub.X(),
    66  		Y:     pub.Y(),
    67  	}, nil
    68  }
    69  
    70  // Sign calculates an ECDSA signature.
    71  //
    72  // This function is susceptible to chosen plaintext attacks that can leak
    73  // information about the private key that is used for signing. Callers must
    74  // be aware that the given hash cannot be chosen by an adversary. Common
    75  // solution is to hash any input before calculating the signature.
    76  //
    77  // The produced signature is in the [R || S || V] format where V is 0 or 1.
    78  func Sign(hash []byte, prv *ecdsa.PrivateKey) ([]byte, error) {
    79  	if len(hash) != 32 {
    80  		return nil, fmt.Errorf("hash is required to be exactly 32 bytes (%d)", len(hash))
    81  	}
    82  	if prv.Curve != S256() {
    83  		return nil, errors.New("private key curve is not secp256k1")
    84  	}
    85  	// ecdsa.PrivateKey -> secp256k1.PrivateKey
    86  	var priv secp256k1.PrivateKey
    87  	if overflow := priv.Key.SetByteSlice(prv.D.Bytes()); overflow || priv.Key.IsZero() {
    88  		return nil, errors.New("invalid private key")
    89  	}
    90  	defer priv.Zero()
    91  	sig := decred_ecdsa.SignCompact(&priv, hash, false) // ref uncompressed pubkey
    92  	// Convert to Ethereum signature format with 'recovery id' v at the end.
    93  	v := sig[0] - 27
    94  	copy(sig, sig[1:])
    95  	sig[RecoveryIDOffset] = v
    96  	return sig, nil
    97  }
    98  
    99  // VerifySignature checks that the given public key created signature over hash.
   100  // The public key should be in compressed (33 bytes) or uncompressed (65 bytes) format.
   101  // The signature should have the 64 byte [R || S] format.
   102  func VerifySignature(pubkey, hash, signature []byte) bool {
   103  	if len(signature) != 64 {
   104  		return false
   105  	}
   106  	var r, s secp256k1.ModNScalar
   107  	if r.SetByteSlice(signature[:32]) {
   108  		return false // overflow
   109  	}
   110  	if s.SetByteSlice(signature[32:]) {
   111  		return false
   112  	}
   113  	sig := decred_ecdsa.NewSignature(&r, &s)
   114  	key, err := secp256k1.ParsePubKey(pubkey)
   115  	if err != nil {
   116  		return false
   117  	}
   118  	// Reject malleable signatures. libsecp256k1 does this check but decred doesn't.
   119  	if s.IsOverHalfOrder() {
   120  		return false
   121  	}
   122  	return sig.Verify(hash, key)
   123  }
   124  
   125  // DecompressPubkey parses a public key in the 33-byte compressed format.
   126  func DecompressPubkey(pubkey []byte) (*ecdsa.PublicKey, error) {
   127  	if len(pubkey) != 33 {
   128  		return nil, errors.New("invalid compressed public key length")
   129  	}
   130  	key, err := secp256k1.ParsePubKey(pubkey)
   131  	if err != nil {
   132  		return nil, err
   133  	}
   134  	// We need to explicitly set the curve here, because we're wrapping
   135  	// the original curve to add (un-)marshalling
   136  	return &ecdsa.PublicKey{
   137  		Curve: S256(),
   138  		X:     key.X(),
   139  		Y:     key.Y(),
   140  	}, nil
   141  }
   142  
   143  // CompressPubkey encodes a public key to the 33-byte compressed format. The
   144  // provided PublicKey must be valid. Namely, the coordinates must not be larger
   145  // than 32 bytes each, they must be less than the field prime, and it must be a
   146  // point on the secp256k1 curve. This is the case for a PublicKey constructed by
   147  // elliptic.Unmarshal (see UnmarshalPubkey), or by ToECDSA and ecdsa.GenerateKey
   148  // when constructing a PrivateKey.
   149  func CompressPubkey(pubkey *ecdsa.PublicKey) []byte {
   150  	// NOTE: the coordinates may be validated with
   151  	// secp256k1.ParsePubKey(FromECDSAPub(pubkey))
   152  	var x, y secp256k1.FieldVal
   153  	x.SetByteSlice(pubkey.X.Bytes())
   154  	y.SetByteSlice(pubkey.Y.Bytes())
   155  	return secp256k1.NewPublicKey(&x, &y).SerializeCompressed()
   156  }
   157  
   158  // S256 returns an instance of the secp256k1 curve.
   159  func S256() EllipticCurve {
   160  	return btCurve{secp256k1.S256()}
   161  }
   162  
   163  type btCurve struct {
   164  	*secp256k1.KoblitzCurve
   165  }
   166  
   167  // Marshal converts a point given as (x, y) into a byte slice.
   168  func (curve btCurve) Marshal(x, y *big.Int) []byte {
   169  	byteLen := (curve.Params().BitSize + 7) / 8
   170  
   171  	ret := make([]byte, 1+2*byteLen)
   172  	ret[0] = 4 // uncompressed point
   173  
   174  	x.FillBytes(ret[1 : 1+byteLen])
   175  	y.FillBytes(ret[1+byteLen : 1+2*byteLen])
   176  
   177  	return ret
   178  }
   179  
   180  // Unmarshal converts a point, serialised by Marshal, into an x, y pair. On
   181  // error, x = nil.
   182  func (curve btCurve) Unmarshal(data []byte) (x, y *big.Int) {
   183  	byteLen := (curve.Params().BitSize + 7) / 8
   184  	if len(data) != 1+2*byteLen {
   185  		return nil, nil
   186  	}
   187  	if data[0] != 4 { // uncompressed form
   188  		return nil, nil
   189  	}
   190  	x = new(big.Int).SetBytes(data[1 : 1+byteLen])
   191  	y = new(big.Int).SetBytes(data[1+byteLen:])
   192  	return
   193  }