github.com/twelsh-aw/go/src@v0.0.0-20230516233729-a56fe86a7c81/crypto/ecdsa/ecdsa.go (about)

     1  // Copyright 2011 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package ecdsa implements the Elliptic Curve Digital Signature Algorithm, as
     6  // defined in FIPS 186-4 and SEC 1, Version 2.0.
     7  //
     8  // Signatures generated by this package are not deterministic, but entropy is
     9  // mixed with the private key and the message, achieving the same level of
    10  // security in case of randomness source failure.
    11  package ecdsa
    12  
    13  // [FIPS 186-4] references ANSI X9.62-2005 for the bulk of the ECDSA algorithm.
    14  // That standard is not freely available, which is a problem in an open source
    15  // implementation, because not only the implementer, but also any maintainer,
    16  // contributor, reviewer, auditor, and learner needs access to it. Instead, this
    17  // package references and follows the equivalent [SEC 1, Version 2.0].
    18  //
    19  // [FIPS 186-4]: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
    20  // [SEC 1, Version 2.0]: https://www.secg.org/sec1-v2.pdf
    21  
    22  import (
    23  	"bytes"
    24  	"crypto"
    25  	"crypto/aes"
    26  	"crypto/cipher"
    27  	"crypto/ecdh"
    28  	"crypto/elliptic"
    29  	"crypto/internal/bigmod"
    30  	"crypto/internal/boring"
    31  	"crypto/internal/boring/bbig"
    32  	"crypto/internal/nistec"
    33  	"crypto/internal/randutil"
    34  	"crypto/sha512"
    35  	"crypto/subtle"
    36  	"errors"
    37  	"io"
    38  	"math/big"
    39  	"sync"
    40  
    41  	"golang.org/x/crypto/cryptobyte"
    42  	"golang.org/x/crypto/cryptobyte/asn1"
    43  )
    44  
    45  // PublicKey represents an ECDSA public key.
    46  type PublicKey struct {
    47  	elliptic.Curve
    48  	X, Y *big.Int
    49  }
    50  
    51  // Any methods implemented on PublicKey might need to also be implemented on
    52  // PrivateKey, as the latter embeds the former and will expose its methods.
    53  
    54  // ECDH returns k as a [ecdh.PublicKey]. It returns an error if the key is
    55  // invalid according to the definition of [ecdh.Curve.NewPublicKey], or if the
    56  // Curve is not supported by crypto/ecdh.
    57  func (k *PublicKey) ECDH() (*ecdh.PublicKey, error) {
    58  	c := curveToECDH(k.Curve)
    59  	if c == nil {
    60  		return nil, errors.New("ecdsa: unsupported curve by crypto/ecdh")
    61  	}
    62  	if !k.Curve.IsOnCurve(k.X, k.Y) {
    63  		return nil, errors.New("ecdsa: invalid public key")
    64  	}
    65  	return c.NewPublicKey(elliptic.Marshal(k.Curve, k.X, k.Y))
    66  }
    67  
    68  // Equal reports whether pub and x have the same value.
    69  //
    70  // Two keys are only considered to have the same value if they have the same Curve value.
    71  // Note that for example elliptic.P256() and elliptic.P256().Params() are different
    72  // values, as the latter is a generic not constant time implementation.
    73  func (pub *PublicKey) Equal(x crypto.PublicKey) bool {
    74  	xx, ok := x.(*PublicKey)
    75  	if !ok {
    76  		return false
    77  	}
    78  	return bigIntEqual(pub.X, xx.X) && bigIntEqual(pub.Y, xx.Y) &&
    79  		// Standard library Curve implementations are singletons, so this check
    80  		// will work for those. Other Curves might be equivalent even if not
    81  		// singletons, but there is no definitive way to check for that, and
    82  		// better to err on the side of safety.
    83  		pub.Curve == xx.Curve
    84  }
    85  
    86  // PrivateKey represents an ECDSA private key.
    87  type PrivateKey struct {
    88  	PublicKey
    89  	D *big.Int
    90  }
    91  
    92  // ECDH returns k as a [ecdh.PrivateKey]. It returns an error if the key is
    93  // invalid according to the definition of [ecdh.Curve.NewPrivateKey], or if the
    94  // Curve is not supported by crypto/ecdh.
    95  func (k *PrivateKey) ECDH() (*ecdh.PrivateKey, error) {
    96  	c := curveToECDH(k.Curve)
    97  	if c == nil {
    98  		return nil, errors.New("ecdsa: unsupported curve by crypto/ecdh")
    99  	}
   100  	size := (k.Curve.Params().N.BitLen() + 7) / 8
   101  	if k.D.BitLen() > size*8 {
   102  		return nil, errors.New("ecdsa: invalid private key")
   103  	}
   104  	return c.NewPrivateKey(k.D.FillBytes(make([]byte, size)))
   105  }
   106  
   107  func curveToECDH(c elliptic.Curve) ecdh.Curve {
   108  	switch c {
   109  	case elliptic.P256():
   110  		return ecdh.P256()
   111  	case elliptic.P384():
   112  		return ecdh.P384()
   113  	case elliptic.P521():
   114  		return ecdh.P521()
   115  	default:
   116  		return nil
   117  	}
   118  }
   119  
   120  // Public returns the public key corresponding to priv.
   121  func (priv *PrivateKey) Public() crypto.PublicKey {
   122  	return &priv.PublicKey
   123  }
   124  
   125  // Equal reports whether priv and x have the same value.
   126  //
   127  // See PublicKey.Equal for details on how Curve is compared.
   128  func (priv *PrivateKey) Equal(x crypto.PrivateKey) bool {
   129  	xx, ok := x.(*PrivateKey)
   130  	if !ok {
   131  		return false
   132  	}
   133  	return priv.PublicKey.Equal(&xx.PublicKey) && bigIntEqual(priv.D, xx.D)
   134  }
   135  
   136  // bigIntEqual reports whether a and b are equal leaking only their bit length
   137  // through timing side-channels.
   138  func bigIntEqual(a, b *big.Int) bool {
   139  	return subtle.ConstantTimeCompare(a.Bytes(), b.Bytes()) == 1
   140  }
   141  
   142  // Sign signs digest with priv, reading randomness from rand. The opts argument
   143  // is not currently used but, in keeping with the crypto.Signer interface,
   144  // should be the hash function used to digest the message.
   145  //
   146  // This method implements crypto.Signer, which is an interface to support keys
   147  // where the private part is kept in, for example, a hardware module. Common
   148  // uses can use the SignASN1 function in this package directly.
   149  func (priv *PrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
   150  	return SignASN1(rand, priv, digest)
   151  }
   152  
   153  // GenerateKey generates a public and private key pair.
   154  func GenerateKey(c elliptic.Curve, rand io.Reader) (*PrivateKey, error) {
   155  	randutil.MaybeReadByte(rand)
   156  
   157  	if boring.Enabled && rand == boring.RandReader {
   158  		x, y, d, err := boring.GenerateKeyECDSA(c.Params().Name)
   159  		if err != nil {
   160  			return nil, err
   161  		}
   162  		return &PrivateKey{PublicKey: PublicKey{Curve: c, X: bbig.Dec(x), Y: bbig.Dec(y)}, D: bbig.Dec(d)}, nil
   163  	}
   164  	boring.UnreachableExceptTests()
   165  
   166  	switch c.Params() {
   167  	case elliptic.P224().Params():
   168  		return generateNISTEC(p224(), rand)
   169  	case elliptic.P256().Params():
   170  		return generateNISTEC(p256(), rand)
   171  	case elliptic.P384().Params():
   172  		return generateNISTEC(p384(), rand)
   173  	case elliptic.P521().Params():
   174  		return generateNISTEC(p521(), rand)
   175  	default:
   176  		return generateLegacy(c, rand)
   177  	}
   178  }
   179  
   180  func generateNISTEC[Point nistPoint[Point]](c *nistCurve[Point], rand io.Reader) (*PrivateKey, error) {
   181  	k, Q, err := randomPoint(c, rand)
   182  	if err != nil {
   183  		return nil, err
   184  	}
   185  
   186  	priv := new(PrivateKey)
   187  	priv.PublicKey.Curve = c.curve
   188  	priv.D = new(big.Int).SetBytes(k.Bytes(c.N))
   189  	priv.PublicKey.X, priv.PublicKey.Y, err = c.pointToAffine(Q)
   190  	if err != nil {
   191  		return nil, err
   192  	}
   193  	return priv, nil
   194  }
   195  
   196  // randomPoint returns a random scalar and the corresponding point using the
   197  // procedure given in FIPS 186-4, Appendix B.5.2 (rejection sampling).
   198  func randomPoint[Point nistPoint[Point]](c *nistCurve[Point], rand io.Reader) (k *bigmod.Nat, p Point, err error) {
   199  	k = bigmod.NewNat()
   200  	for {
   201  		b := make([]byte, c.N.Size())
   202  		if _, err = io.ReadFull(rand, b); err != nil {
   203  			return
   204  		}
   205  
   206  		// Mask off any excess bits to increase the chance of hitting a value in
   207  		// (0, N). These are the most dangerous lines in the package and maybe in
   208  		// the library: a single bit of bias in the selection of nonces would likely
   209  		// lead to key recovery, but no tests would fail. Look but DO NOT TOUCH.
   210  		if excess := len(b)*8 - c.N.BitLen(); excess > 0 {
   211  			// Just to be safe, assert that this only happens for the one curve that
   212  			// doesn't have a round number of bits.
   213  			if excess != 0 && c.curve.Params().Name != "P-521" {
   214  				panic("ecdsa: internal error: unexpectedly masking off bits")
   215  			}
   216  			b[0] >>= excess
   217  		}
   218  
   219  		// FIPS 186-4 makes us check k <= N - 2 and then add one.
   220  		// Checking 0 < k <= N - 1 is strictly equivalent.
   221  		// None of this matters anyway because the chance of selecting
   222  		// zero is cryptographically negligible.
   223  		if _, err = k.SetBytes(b, c.N); err == nil && k.IsZero() == 0 {
   224  			break
   225  		}
   226  
   227  		if testingOnlyRejectionSamplingLooped != nil {
   228  			testingOnlyRejectionSamplingLooped()
   229  		}
   230  	}
   231  
   232  	p, err = c.newPoint().ScalarBaseMult(k.Bytes(c.N))
   233  	return
   234  }
   235  
   236  // testingOnlyRejectionSamplingLooped is called when rejection sampling in
   237  // randomPoint rejects a candidate for being higher than the modulus.
   238  var testingOnlyRejectionSamplingLooped func()
   239  
   240  // errNoAsm is returned by signAsm and verifyAsm when the assembly
   241  // implementation is not available.
   242  var errNoAsm = errors.New("no assembly implementation available")
   243  
   244  // SignASN1 signs a hash (which should be the result of hashing a larger message)
   245  // using the private key, priv. If the hash is longer than the bit-length of the
   246  // private key's curve order, the hash will be truncated to that length. It
   247  // returns the ASN.1 encoded signature.
   248  func SignASN1(rand io.Reader, priv *PrivateKey, hash []byte) ([]byte, error) {
   249  	randutil.MaybeReadByte(rand)
   250  
   251  	if boring.Enabled && rand == boring.RandReader {
   252  		b, err := boringPrivateKey(priv)
   253  		if err != nil {
   254  			return nil, err
   255  		}
   256  		return boring.SignMarshalECDSA(b, hash)
   257  	}
   258  	boring.UnreachableExceptTests()
   259  
   260  	csprng, err := mixedCSPRNG(rand, priv, hash)
   261  	if err != nil {
   262  		return nil, err
   263  	}
   264  
   265  	if sig, err := signAsm(priv, csprng, hash); err != errNoAsm {
   266  		return sig, err
   267  	}
   268  
   269  	switch priv.Curve.Params() {
   270  	case elliptic.P224().Params():
   271  		return signNISTEC(p224(), priv, csprng, hash)
   272  	case elliptic.P256().Params():
   273  		return signNISTEC(p256(), priv, csprng, hash)
   274  	case elliptic.P384().Params():
   275  		return signNISTEC(p384(), priv, csprng, hash)
   276  	case elliptic.P521().Params():
   277  		return signNISTEC(p521(), priv, csprng, hash)
   278  	default:
   279  		return signLegacy(priv, csprng, hash)
   280  	}
   281  }
   282  
   283  func signNISTEC[Point nistPoint[Point]](c *nistCurve[Point], priv *PrivateKey, csprng io.Reader, hash []byte) (sig []byte, err error) {
   284  	// SEC 1, Version 2.0, Section 4.1.3
   285  
   286  	k, R, err := randomPoint(c, csprng)
   287  	if err != nil {
   288  		return nil, err
   289  	}
   290  
   291  	// kInv = k⁻¹
   292  	kInv := bigmod.NewNat()
   293  	inverse(c, kInv, k)
   294  
   295  	Rx, err := R.BytesX()
   296  	if err != nil {
   297  		return nil, err
   298  	}
   299  	r, err := bigmod.NewNat().SetOverflowingBytes(Rx, c.N)
   300  	if err != nil {
   301  		return nil, err
   302  	}
   303  
   304  	// The spec wants us to retry here, but the chance of hitting this condition
   305  	// on a large prime-order group like the NIST curves we support is
   306  	// cryptographically negligible. If we hit it, something is awfully wrong.
   307  	if r.IsZero() == 1 {
   308  		return nil, errors.New("ecdsa: internal error: r is zero")
   309  	}
   310  
   311  	e := bigmod.NewNat()
   312  	hashToNat(c, e, hash)
   313  
   314  	s, err := bigmod.NewNat().SetBytes(priv.D.Bytes(), c.N)
   315  	if err != nil {
   316  		return nil, err
   317  	}
   318  	s.Mul(r, c.N)
   319  	s.Add(e, c.N)
   320  	s.Mul(kInv, c.N)
   321  
   322  	// Again, the chance of this happening is cryptographically negligible.
   323  	if s.IsZero() == 1 {
   324  		return nil, errors.New("ecdsa: internal error: s is zero")
   325  	}
   326  
   327  	return encodeSignature(r.Bytes(c.N), s.Bytes(c.N))
   328  }
   329  
   330  func encodeSignature(r, s []byte) ([]byte, error) {
   331  	var b cryptobyte.Builder
   332  	b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
   333  		addASN1IntBytes(b, r)
   334  		addASN1IntBytes(b, s)
   335  	})
   336  	return b.Bytes()
   337  }
   338  
   339  // addASN1IntBytes encodes in ASN.1 a positive integer represented as
   340  // a big-endian byte slice with zero or more leading zeroes.
   341  func addASN1IntBytes(b *cryptobyte.Builder, bytes []byte) {
   342  	for len(bytes) > 0 && bytes[0] == 0 {
   343  		bytes = bytes[1:]
   344  	}
   345  	if len(bytes) == 0 {
   346  		b.SetError(errors.New("invalid integer"))
   347  		return
   348  	}
   349  	b.AddASN1(asn1.INTEGER, func(c *cryptobyte.Builder) {
   350  		if bytes[0]&0x80 != 0 {
   351  			c.AddUint8(0)
   352  		}
   353  		c.AddBytes(bytes)
   354  	})
   355  }
   356  
   357  // inverse sets kInv to the inverse of k modulo the order of the curve.
   358  func inverse[Point nistPoint[Point]](c *nistCurve[Point], kInv, k *bigmod.Nat) {
   359  	if c.curve.Params().Name == "P-256" {
   360  		kBytes, err := nistec.P256OrdInverse(k.Bytes(c.N))
   361  		// Some platforms don't implement P256OrdInverse, and always return an error.
   362  		if err == nil {
   363  			_, err := kInv.SetBytes(kBytes, c.N)
   364  			if err != nil {
   365  				panic("ecdsa: internal error: P256OrdInverse produced an invalid value")
   366  			}
   367  			return
   368  		}
   369  	}
   370  
   371  	// Calculate the inverse of s in GF(N) using Fermat's method
   372  	// (exponentiation modulo P - 2, per Euler's theorem)
   373  	kInv.Exp(k, c.nMinus2, c.N)
   374  }
   375  
   376  // hashToNat sets e to the left-most bits of hash, according to
   377  // SEC 1, Section 4.1.3, point 5 and Section 4.1.4, point 3.
   378  func hashToNat[Point nistPoint[Point]](c *nistCurve[Point], e *bigmod.Nat, hash []byte) {
   379  	// ECDSA asks us to take the left-most log2(N) bits of hash, and use them as
   380  	// an integer modulo N. This is the absolute worst of all worlds: we still
   381  	// have to reduce, because the result might still overflow N, but to take
   382  	// the left-most bits for P-521 we have to do a right shift.
   383  	if size := c.N.Size(); len(hash) > size {
   384  		hash = hash[:size]
   385  		if excess := len(hash)*8 - c.N.BitLen(); excess > 0 {
   386  			hash = bytes.Clone(hash)
   387  			for i := len(hash) - 1; i >= 0; i-- {
   388  				hash[i] >>= excess
   389  				if i > 0 {
   390  					hash[i] |= hash[i-1] << (8 - excess)
   391  				}
   392  			}
   393  		}
   394  	}
   395  	_, err := e.SetOverflowingBytes(hash, c.N)
   396  	if err != nil {
   397  		panic("ecdsa: internal error: truncated hash is too long")
   398  	}
   399  }
   400  
   401  // mixedCSPRNG returns a CSPRNG that mixes entropy from rand with the message
   402  // and the private key, to protect the key in case rand fails. This is
   403  // equivalent in security to RFC 6979 deterministic nonce generation, but still
   404  // produces randomized signatures.
   405  func mixedCSPRNG(rand io.Reader, priv *PrivateKey, hash []byte) (io.Reader, error) {
   406  	// This implementation derives the nonce from an AES-CTR CSPRNG keyed by:
   407  	//
   408  	//    SHA2-512(priv.D || entropy || hash)[:32]
   409  	//
   410  	// The CSPRNG key is indifferentiable from a random oracle as shown in
   411  	// [Coron], the AES-CTR stream is indifferentiable from a random oracle
   412  	// under standard cryptographic assumptions (see [Larsson] for examples).
   413  	//
   414  	// [Coron]: https://cs.nyu.edu/~dodis/ps/merkle.pdf
   415  	// [Larsson]: https://web.archive.org/web/20040719170906/https://www.nada.kth.se/kurser/kth/2D1441/semteo03/lecturenotes/assump.pdf
   416  
   417  	// Get 256 bits of entropy from rand.
   418  	entropy := make([]byte, 32)
   419  	if _, err := io.ReadFull(rand, entropy); err != nil {
   420  		return nil, err
   421  	}
   422  
   423  	// Initialize an SHA-512 hash context; digest...
   424  	md := sha512.New()
   425  	md.Write(priv.D.Bytes()) // the private key,
   426  	md.Write(entropy)        // the entropy,
   427  	md.Write(hash)           // and the input hash;
   428  	key := md.Sum(nil)[:32]  // and compute ChopMD-256(SHA-512),
   429  	// which is an indifferentiable MAC.
   430  
   431  	// Create an AES-CTR instance to use as a CSPRNG.
   432  	block, err := aes.NewCipher(key)
   433  	if err != nil {
   434  		return nil, err
   435  	}
   436  
   437  	// Create a CSPRNG that xors a stream of zeros with
   438  	// the output of the AES-CTR instance.
   439  	const aesIV = "IV for ECDSA CTR"
   440  	return &cipher.StreamReader{
   441  		R: zeroReader,
   442  		S: cipher.NewCTR(block, []byte(aesIV)),
   443  	}, nil
   444  }
   445  
   446  type zr struct{}
   447  
   448  var zeroReader = zr{}
   449  
   450  // Read replaces the contents of dst with zeros. It is safe for concurrent use.
   451  func (zr) Read(dst []byte) (n int, err error) {
   452  	for i := range dst {
   453  		dst[i] = 0
   454  	}
   455  	return len(dst), nil
   456  }
   457  
   458  // VerifyASN1 verifies the ASN.1 encoded signature, sig, of hash using the
   459  // public key, pub. Its return value records whether the signature is valid.
   460  func VerifyASN1(pub *PublicKey, hash, sig []byte) bool {
   461  	if boring.Enabled {
   462  		key, err := boringPublicKey(pub)
   463  		if err != nil {
   464  			return false
   465  		}
   466  		return boring.VerifyECDSA(key, hash, sig)
   467  	}
   468  	boring.UnreachableExceptTests()
   469  
   470  	if err := verifyAsm(pub, hash, sig); err != errNoAsm {
   471  		return err == nil
   472  	}
   473  
   474  	switch pub.Curve.Params() {
   475  	case elliptic.P224().Params():
   476  		return verifyNISTEC(p224(), pub, hash, sig)
   477  	case elliptic.P256().Params():
   478  		return verifyNISTEC(p256(), pub, hash, sig)
   479  	case elliptic.P384().Params():
   480  		return verifyNISTEC(p384(), pub, hash, sig)
   481  	case elliptic.P521().Params():
   482  		return verifyNISTEC(p521(), pub, hash, sig)
   483  	default:
   484  		return verifyLegacy(pub, hash, sig)
   485  	}
   486  }
   487  
   488  func verifyNISTEC[Point nistPoint[Point]](c *nistCurve[Point], pub *PublicKey, hash, sig []byte) bool {
   489  	rBytes, sBytes, err := parseSignature(sig)
   490  	if err != nil {
   491  		return false
   492  	}
   493  
   494  	Q, err := c.pointFromAffine(pub.X, pub.Y)
   495  	if err != nil {
   496  		return false
   497  	}
   498  
   499  	// SEC 1, Version 2.0, Section 4.1.4
   500  
   501  	r, err := bigmod.NewNat().SetBytes(rBytes, c.N)
   502  	if err != nil || r.IsZero() == 1 {
   503  		return false
   504  	}
   505  	s, err := bigmod.NewNat().SetBytes(sBytes, c.N)
   506  	if err != nil || s.IsZero() == 1 {
   507  		return false
   508  	}
   509  
   510  	e := bigmod.NewNat()
   511  	hashToNat(c, e, hash)
   512  
   513  	// w = s⁻¹
   514  	w := bigmod.NewNat()
   515  	inverse(c, w, s)
   516  
   517  	// p₁ = [e * s⁻¹]G
   518  	p1, err := c.newPoint().ScalarBaseMult(e.Mul(w, c.N).Bytes(c.N))
   519  	if err != nil {
   520  		return false
   521  	}
   522  	// p₂ = [r * s⁻¹]Q
   523  	p2, err := Q.ScalarMult(Q, w.Mul(r, c.N).Bytes(c.N))
   524  	if err != nil {
   525  		return false
   526  	}
   527  	// BytesX returns an error for the point at infinity.
   528  	Rx, err := p1.Add(p1, p2).BytesX()
   529  	if err != nil {
   530  		return false
   531  	}
   532  
   533  	v, err := bigmod.NewNat().SetOverflowingBytes(Rx, c.N)
   534  	if err != nil {
   535  		return false
   536  	}
   537  
   538  	return v.Equal(r) == 1
   539  }
   540  
   541  func parseSignature(sig []byte) (r, s []byte, err error) {
   542  	var inner cryptobyte.String
   543  	input := cryptobyte.String(sig)
   544  	if !input.ReadASN1(&inner, asn1.SEQUENCE) ||
   545  		!input.Empty() ||
   546  		!inner.ReadASN1Integer(&r) ||
   547  		!inner.ReadASN1Integer(&s) ||
   548  		!inner.Empty() {
   549  		return nil, nil, errors.New("invalid ASN.1")
   550  	}
   551  	return r, s, nil
   552  }
   553  
   554  type nistCurve[Point nistPoint[Point]] struct {
   555  	newPoint func() Point
   556  	curve    elliptic.Curve
   557  	N        *bigmod.Modulus
   558  	nMinus2  []byte
   559  }
   560  
   561  // nistPoint is a generic constraint for the nistec Point types.
   562  type nistPoint[T any] interface {
   563  	Bytes() []byte
   564  	BytesX() ([]byte, error)
   565  	SetBytes([]byte) (T, error)
   566  	Add(T, T) T
   567  	ScalarMult(T, []byte) (T, error)
   568  	ScalarBaseMult([]byte) (T, error)
   569  }
   570  
   571  // pointFromAffine is used to convert the PublicKey to a nistec Point.
   572  func (curve *nistCurve[Point]) pointFromAffine(x, y *big.Int) (p Point, err error) {
   573  	bitSize := curve.curve.Params().BitSize
   574  	// Reject values that would not get correctly encoded.
   575  	if x.Sign() < 0 || y.Sign() < 0 {
   576  		return p, errors.New("negative coordinate")
   577  	}
   578  	if x.BitLen() > bitSize || y.BitLen() > bitSize {
   579  		return p, errors.New("overflowing coordinate")
   580  	}
   581  	// Encode the coordinates and let SetBytes reject invalid points.
   582  	byteLen := (bitSize + 7) / 8
   583  	buf := make([]byte, 1+2*byteLen)
   584  	buf[0] = 4 // uncompressed point
   585  	x.FillBytes(buf[1 : 1+byteLen])
   586  	y.FillBytes(buf[1+byteLen : 1+2*byteLen])
   587  	return curve.newPoint().SetBytes(buf)
   588  }
   589  
   590  // pointToAffine is used to convert a nistec Point to a PublicKey.
   591  func (curve *nistCurve[Point]) pointToAffine(p Point) (x, y *big.Int, err error) {
   592  	out := p.Bytes()
   593  	if len(out) == 1 && out[0] == 0 {
   594  		// This is the encoding of the point at infinity.
   595  		return nil, nil, errors.New("ecdsa: public key point is the infinity")
   596  	}
   597  	byteLen := (curve.curve.Params().BitSize + 7) / 8
   598  	x = new(big.Int).SetBytes(out[1 : 1+byteLen])
   599  	y = new(big.Int).SetBytes(out[1+byteLen:])
   600  	return x, y, nil
   601  }
   602  
   603  var p224Once sync.Once
   604  var _p224 *nistCurve[*nistec.P224Point]
   605  
   606  func p224() *nistCurve[*nistec.P224Point] {
   607  	p224Once.Do(func() {
   608  		_p224 = &nistCurve[*nistec.P224Point]{
   609  			newPoint: func() *nistec.P224Point { return nistec.NewP224Point() },
   610  		}
   611  		precomputeParams(_p224, elliptic.P224())
   612  	})
   613  	return _p224
   614  }
   615  
   616  var p256Once sync.Once
   617  var _p256 *nistCurve[*nistec.P256Point]
   618  
   619  func p256() *nistCurve[*nistec.P256Point] {
   620  	p256Once.Do(func() {
   621  		_p256 = &nistCurve[*nistec.P256Point]{
   622  			newPoint: func() *nistec.P256Point { return nistec.NewP256Point() },
   623  		}
   624  		precomputeParams(_p256, elliptic.P256())
   625  	})
   626  	return _p256
   627  }
   628  
   629  var p384Once sync.Once
   630  var _p384 *nistCurve[*nistec.P384Point]
   631  
   632  func p384() *nistCurve[*nistec.P384Point] {
   633  	p384Once.Do(func() {
   634  		_p384 = &nistCurve[*nistec.P384Point]{
   635  			newPoint: func() *nistec.P384Point { return nistec.NewP384Point() },
   636  		}
   637  		precomputeParams(_p384, elliptic.P384())
   638  	})
   639  	return _p384
   640  }
   641  
   642  var p521Once sync.Once
   643  var _p521 *nistCurve[*nistec.P521Point]
   644  
   645  func p521() *nistCurve[*nistec.P521Point] {
   646  	p521Once.Do(func() {
   647  		_p521 = &nistCurve[*nistec.P521Point]{
   648  			newPoint: func() *nistec.P521Point { return nistec.NewP521Point() },
   649  		}
   650  		precomputeParams(_p521, elliptic.P521())
   651  	})
   652  	return _p521
   653  }
   654  
   655  func precomputeParams[Point nistPoint[Point]](c *nistCurve[Point], curve elliptic.Curve) {
   656  	params := curve.Params()
   657  	c.curve = curve
   658  	c.N = bigmod.NewModulusFromBig(params.N)
   659  	c.nMinus2 = new(big.Int).Sub(params.N, big.NewInt(2)).Bytes()
   660  }