Source file src/crypto/ecdsa/ecdsa.go

     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 new ECDSA private key for the specified curve.
   154  //
   155  // Most applications should use [crypto/rand.Reader] as rand. Note that the
   156  // returned key does not depend deterministically on the bytes read from rand,
   157  // and may change between calls and/or between versions.
   158  func GenerateKey(c elliptic.Curve, rand io.Reader) (*PrivateKey, error) {
   159  	randutil.MaybeReadByte(rand)
   160  
   161  	if boring.Enabled && rand == boring.RandReader {
   162  		x, y, d, err := boring.GenerateKeyECDSA(c.Params().Name)
   163  		if err != nil {
   164  			return nil, err
   165  		}
   166  		return &PrivateKey{PublicKey: PublicKey{Curve: c, X: bbig.Dec(x), Y: bbig.Dec(y)}, D: bbig.Dec(d)}, nil
   167  	}
   168  	boring.UnreachableExceptTests()
   169  
   170  	switch c.Params() {
   171  	case elliptic.P224().Params():
   172  		return generateNISTEC(p224(), rand)
   173  	case elliptic.P256().Params():
   174  		return generateNISTEC(p256(), rand)
   175  	case elliptic.P384().Params():
   176  		return generateNISTEC(p384(), rand)
   177  	case elliptic.P521().Params():
   178  		return generateNISTEC(p521(), rand)
   179  	default:
   180  		return generateLegacy(c, rand)
   181  	}
   182  }
   183  
   184  func generateNISTEC[Point nistPoint[Point]](c *nistCurve[Point], rand io.Reader) (*PrivateKey, error) {
   185  	k, Q, err := randomPoint(c, rand)
   186  	if err != nil {
   187  		return nil, err
   188  	}
   189  
   190  	priv := new(PrivateKey)
   191  	priv.PublicKey.Curve = c.curve
   192  	priv.D = new(big.Int).SetBytes(k.Bytes(c.N))
   193  	priv.PublicKey.X, priv.PublicKey.Y, err = c.pointToAffine(Q)
   194  	if err != nil {
   195  		return nil, err
   196  	}
   197  	return priv, nil
   198  }
   199  
   200  // randomPoint returns a random scalar and the corresponding point using the
   201  // procedure given in FIPS 186-4, Appendix B.5.2 (rejection sampling).
   202  func randomPoint[Point nistPoint[Point]](c *nistCurve[Point], rand io.Reader) (k *bigmod.Nat, p Point, err error) {
   203  	k = bigmod.NewNat()
   204  	for {
   205  		b := make([]byte, c.N.Size())
   206  		if _, err = io.ReadFull(rand, b); err != nil {
   207  			return
   208  		}
   209  
   210  		// Mask off any excess bits to increase the chance of hitting a value in
   211  		// (0, N). These are the most dangerous lines in the package and maybe in
   212  		// the library: a single bit of bias in the selection of nonces would likely
   213  		// lead to key recovery, but no tests would fail. Look but DO NOT TOUCH.
   214  		if excess := len(b)*8 - c.N.BitLen(); excess > 0 {
   215  			// Just to be safe, assert that this only happens for the one curve that
   216  			// doesn't have a round number of bits.
   217  			if excess != 0 && c.curve.Params().Name != "P-521" {
   218  				panic("ecdsa: internal error: unexpectedly masking off bits")
   219  			}
   220  			b[0] >>= excess
   221  		}
   222  
   223  		// FIPS 186-4 makes us check k <= N - 2 and then add one.
   224  		// Checking 0 < k <= N - 1 is strictly equivalent.
   225  		// None of this matters anyway because the chance of selecting
   226  		// zero is cryptographically negligible.
   227  		if _, err = k.SetBytes(b, c.N); err == nil && k.IsZero() == 0 {
   228  			break
   229  		}
   230  
   231  		if testingOnlyRejectionSamplingLooped != nil {
   232  			testingOnlyRejectionSamplingLooped()
   233  		}
   234  	}
   235  
   236  	p, err = c.newPoint().ScalarBaseMult(k.Bytes(c.N))
   237  	return
   238  }
   239  
   240  // testingOnlyRejectionSamplingLooped is called when rejection sampling in
   241  // randomPoint rejects a candidate for being higher than the modulus.
   242  var testingOnlyRejectionSamplingLooped func()
   243  
   244  // errNoAsm is returned by signAsm and verifyAsm when the assembly
   245  // implementation is not available.
   246  var errNoAsm = errors.New("no assembly implementation available")
   247  
   248  // SignASN1 signs a hash (which should be the result of hashing a larger message)
   249  // using the private key, priv. If the hash is longer than the bit-length of the
   250  // private key's curve order, the hash will be truncated to that length. It
   251  // returns the ASN.1 encoded signature.
   252  //
   253  // The signature is randomized. Most applications should use [crypto/rand.Reader]
   254  // as rand. Note that the returned signature does not depend deterministically on
   255  // the bytes read from rand, and may change between calls and/or between versions.
   256  func SignASN1(rand io.Reader, priv *PrivateKey, hash []byte) ([]byte, error) {
   257  	randutil.MaybeReadByte(rand)
   258  
   259  	if boring.Enabled && rand == boring.RandReader {
   260  		b, err := boringPrivateKey(priv)
   261  		if err != nil {
   262  			return nil, err
   263  		}
   264  		return boring.SignMarshalECDSA(b, hash)
   265  	}
   266  	boring.UnreachableExceptTests()
   267  
   268  	csprng, err := mixedCSPRNG(rand, priv, hash)
   269  	if err != nil {
   270  		return nil, err
   271  	}
   272  
   273  	if sig, err := signAsm(priv, csprng, hash); err != errNoAsm {
   274  		return sig, err
   275  	}
   276  
   277  	switch priv.Curve.Params() {
   278  	case elliptic.P224().Params():
   279  		return signNISTEC(p224(), priv, csprng, hash)
   280  	case elliptic.P256().Params():
   281  		return signNISTEC(p256(), priv, csprng, hash)
   282  	case elliptic.P384().Params():
   283  		return signNISTEC(p384(), priv, csprng, hash)
   284  	case elliptic.P521().Params():
   285  		return signNISTEC(p521(), priv, csprng, hash)
   286  	default:
   287  		return signLegacy(priv, csprng, hash)
   288  	}
   289  }
   290  
   291  func signNISTEC[Point nistPoint[Point]](c *nistCurve[Point], priv *PrivateKey, csprng io.Reader, hash []byte) (sig []byte, err error) {
   292  	// SEC 1, Version 2.0, Section 4.1.3
   293  
   294  	k, R, err := randomPoint(c, csprng)
   295  	if err != nil {
   296  		return nil, err
   297  	}
   298  
   299  	// kInv = k⁻¹
   300  	kInv := bigmod.NewNat()
   301  	inverse(c, kInv, k)
   302  
   303  	Rx, err := R.BytesX()
   304  	if err != nil {
   305  		return nil, err
   306  	}
   307  	r, err := bigmod.NewNat().SetOverflowingBytes(Rx, c.N)
   308  	if err != nil {
   309  		return nil, err
   310  	}
   311  
   312  	// The spec wants us to retry here, but the chance of hitting this condition
   313  	// on a large prime-order group like the NIST curves we support is
   314  	// cryptographically negligible. If we hit it, something is awfully wrong.
   315  	if r.IsZero() == 1 {
   316  		return nil, errors.New("ecdsa: internal error: r is zero")
   317  	}
   318  
   319  	e := bigmod.NewNat()
   320  	hashToNat(c, e, hash)
   321  
   322  	s, err := bigmod.NewNat().SetBytes(priv.D.Bytes(), c.N)
   323  	if err != nil {
   324  		return nil, err
   325  	}
   326  	s.Mul(r, c.N)
   327  	s.Add(e, c.N)
   328  	s.Mul(kInv, c.N)
   329  
   330  	// Again, the chance of this happening is cryptographically negligible.
   331  	if s.IsZero() == 1 {
   332  		return nil, errors.New("ecdsa: internal error: s is zero")
   333  	}
   334  
   335  	return encodeSignature(r.Bytes(c.N), s.Bytes(c.N))
   336  }
   337  
   338  func encodeSignature(r, s []byte) ([]byte, error) {
   339  	var b cryptobyte.Builder
   340  	b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
   341  		addASN1IntBytes(b, r)
   342  		addASN1IntBytes(b, s)
   343  	})
   344  	return b.Bytes()
   345  }
   346  
   347  // addASN1IntBytes encodes in ASN.1 a positive integer represented as
   348  // a big-endian byte slice with zero or more leading zeroes.
   349  func addASN1IntBytes(b *cryptobyte.Builder, bytes []byte) {
   350  	for len(bytes) > 0 && bytes[0] == 0 {
   351  		bytes = bytes[1:]
   352  	}
   353  	if len(bytes) == 0 {
   354  		b.SetError(errors.New("invalid integer"))
   355  		return
   356  	}
   357  	b.AddASN1(asn1.INTEGER, func(c *cryptobyte.Builder) {
   358  		if bytes[0]&0x80 != 0 {
   359  			c.AddUint8(0)
   360  		}
   361  		c.AddBytes(bytes)
   362  	})
   363  }
   364  
   365  // inverse sets kInv to the inverse of k modulo the order of the curve.
   366  func inverse[Point nistPoint[Point]](c *nistCurve[Point], kInv, k *bigmod.Nat) {
   367  	if c.curve.Params().Name == "P-256" {
   368  		kBytes, err := nistec.P256OrdInverse(k.Bytes(c.N))
   369  		// Some platforms don't implement P256OrdInverse, and always return an error.
   370  		if err == nil {
   371  			_, err := kInv.SetBytes(kBytes, c.N)
   372  			if err != nil {
   373  				panic("ecdsa: internal error: P256OrdInverse produced an invalid value")
   374  			}
   375  			return
   376  		}
   377  	}
   378  
   379  	// Calculate the inverse of s in GF(N) using Fermat's method
   380  	// (exponentiation modulo P - 2, per Euler's theorem)
   381  	kInv.Exp(k, c.nMinus2, c.N)
   382  }
   383  
   384  // hashToNat sets e to the left-most bits of hash, according to
   385  // SEC 1, Section 4.1.3, point 5 and Section 4.1.4, point 3.
   386  func hashToNat[Point nistPoint[Point]](c *nistCurve[Point], e *bigmod.Nat, hash []byte) {
   387  	// ECDSA asks us to take the left-most log2(N) bits of hash, and use them as
   388  	// an integer modulo N. This is the absolute worst of all worlds: we still
   389  	// have to reduce, because the result might still overflow N, but to take
   390  	// the left-most bits for P-521 we have to do a right shift.
   391  	if size := c.N.Size(); len(hash) >= size {
   392  		hash = hash[:size]
   393  		if excess := len(hash)*8 - c.N.BitLen(); excess > 0 {
   394  			hash = bytes.Clone(hash)
   395  			for i := len(hash) - 1; i >= 0; i-- {
   396  				hash[i] >>= excess
   397  				if i > 0 {
   398  					hash[i] |= hash[i-1] << (8 - excess)
   399  				}
   400  			}
   401  		}
   402  	}
   403  	_, err := e.SetOverflowingBytes(hash, c.N)
   404  	if err != nil {
   405  		panic("ecdsa: internal error: truncated hash is too long")
   406  	}
   407  }
   408  
   409  // mixedCSPRNG returns a CSPRNG that mixes entropy from rand with the message
   410  // and the private key, to protect the key in case rand fails. This is
   411  // equivalent in security to RFC 6979 deterministic nonce generation, but still
   412  // produces randomized signatures.
   413  func mixedCSPRNG(rand io.Reader, priv *PrivateKey, hash []byte) (io.Reader, error) {
   414  	// This implementation derives the nonce from an AES-CTR CSPRNG keyed by:
   415  	//
   416  	//    SHA2-512(priv.D || entropy || hash)[:32]
   417  	//
   418  	// The CSPRNG key is indifferentiable from a random oracle as shown in
   419  	// [Coron], the AES-CTR stream is indifferentiable from a random oracle
   420  	// under standard cryptographic assumptions (see [Larsson] for examples).
   421  	//
   422  	// [Coron]: https://cs.nyu.edu/~dodis/ps/merkle.pdf
   423  	// [Larsson]: https://web.archive.org/web/20040719170906/https://www.nada.kth.se/kurser/kth/2D1441/semteo03/lecturenotes/assump.pdf
   424  
   425  	// Get 256 bits of entropy from rand.
   426  	entropy := make([]byte, 32)
   427  	if _, err := io.ReadFull(rand, entropy); err != nil {
   428  		return nil, err
   429  	}
   430  
   431  	// Initialize an SHA-512 hash context; digest...
   432  	md := sha512.New()
   433  	md.Write(priv.D.Bytes()) // the private key,
   434  	md.Write(entropy)        // the entropy,
   435  	md.Write(hash)           // and the input hash;
   436  	key := md.Sum(nil)[:32]  // and compute ChopMD-256(SHA-512),
   437  	// which is an indifferentiable MAC.
   438  
   439  	// Create an AES-CTR instance to use as a CSPRNG.
   440  	block, err := aes.NewCipher(key)
   441  	if err != nil {
   442  		return nil, err
   443  	}
   444  
   445  	// Create a CSPRNG that xors a stream of zeros with
   446  	// the output of the AES-CTR instance.
   447  	const aesIV = "IV for ECDSA CTR"
   448  	return &cipher.StreamReader{
   449  		R: zeroReader,
   450  		S: cipher.NewCTR(block, []byte(aesIV)),
   451  	}, nil
   452  }
   453  
   454  type zr struct{}
   455  
   456  var zeroReader = zr{}
   457  
   458  // Read replaces the contents of dst with zeros. It is safe for concurrent use.
   459  func (zr) Read(dst []byte) (n int, err error) {
   460  	for i := range dst {
   461  		dst[i] = 0
   462  	}
   463  	return len(dst), nil
   464  }
   465  
   466  // VerifyASN1 verifies the ASN.1 encoded signature, sig, of hash using the
   467  // public key, pub. Its return value records whether the signature is valid.
   468  func VerifyASN1(pub *PublicKey, hash, sig []byte) bool {
   469  	if boring.Enabled {
   470  		key, err := boringPublicKey(pub)
   471  		if err != nil {
   472  			return false
   473  		}
   474  		return boring.VerifyECDSA(key, hash, sig)
   475  	}
   476  	boring.UnreachableExceptTests()
   477  
   478  	if err := verifyAsm(pub, hash, sig); err != errNoAsm {
   479  		return err == nil
   480  	}
   481  
   482  	switch pub.Curve.Params() {
   483  	case elliptic.P224().Params():
   484  		return verifyNISTEC(p224(), pub, hash, sig)
   485  	case elliptic.P256().Params():
   486  		return verifyNISTEC(p256(), pub, hash, sig)
   487  	case elliptic.P384().Params():
   488  		return verifyNISTEC(p384(), pub, hash, sig)
   489  	case elliptic.P521().Params():
   490  		return verifyNISTEC(p521(), pub, hash, sig)
   491  	default:
   492  		return verifyLegacy(pub, hash, sig)
   493  	}
   494  }
   495  
   496  func verifyNISTEC[Point nistPoint[Point]](c *nistCurve[Point], pub *PublicKey, hash, sig []byte) bool {
   497  	rBytes, sBytes, err := parseSignature(sig)
   498  	if err != nil {
   499  		return false
   500  	}
   501  
   502  	Q, err := c.pointFromAffine(pub.X, pub.Y)
   503  	if err != nil {
   504  		return false
   505  	}
   506  
   507  	// SEC 1, Version 2.0, Section 4.1.4
   508  
   509  	r, err := bigmod.NewNat().SetBytes(rBytes, c.N)
   510  	if err != nil || r.IsZero() == 1 {
   511  		return false
   512  	}
   513  	s, err := bigmod.NewNat().SetBytes(sBytes, c.N)
   514  	if err != nil || s.IsZero() == 1 {
   515  		return false
   516  	}
   517  
   518  	e := bigmod.NewNat()
   519  	hashToNat(c, e, hash)
   520  
   521  	// w = s⁻¹
   522  	w := bigmod.NewNat()
   523  	inverse(c, w, s)
   524  
   525  	// p₁ = [e * s⁻¹]G
   526  	p1, err := c.newPoint().ScalarBaseMult(e.Mul(w, c.N).Bytes(c.N))
   527  	if err != nil {
   528  		return false
   529  	}
   530  	// p₂ = [r * s⁻¹]Q
   531  	p2, err := Q.ScalarMult(Q, w.Mul(r, c.N).Bytes(c.N))
   532  	if err != nil {
   533  		return false
   534  	}
   535  	// BytesX returns an error for the point at infinity.
   536  	Rx, err := p1.Add(p1, p2).BytesX()
   537  	if err != nil {
   538  		return false
   539  	}
   540  
   541  	v, err := bigmod.NewNat().SetOverflowingBytes(Rx, c.N)
   542  	if err != nil {
   543  		return false
   544  	}
   545  
   546  	return v.Equal(r) == 1
   547  }
   548  
   549  func parseSignature(sig []byte) (r, s []byte, err error) {
   550  	var inner cryptobyte.String
   551  	input := cryptobyte.String(sig)
   552  	if !input.ReadASN1(&inner, asn1.SEQUENCE) ||
   553  		!input.Empty() ||
   554  		!inner.ReadASN1Integer(&r) ||
   555  		!inner.ReadASN1Integer(&s) ||
   556  		!inner.Empty() {
   557  		return nil, nil, errors.New("invalid ASN.1")
   558  	}
   559  	return r, s, nil
   560  }
   561  
   562  type nistCurve[Point nistPoint[Point]] struct {
   563  	newPoint func() Point
   564  	curve    elliptic.Curve
   565  	N        *bigmod.Modulus
   566  	nMinus2  []byte
   567  }
   568  
   569  // nistPoint is a generic constraint for the nistec Point types.
   570  type nistPoint[T any] interface {
   571  	Bytes() []byte
   572  	BytesX() ([]byte, error)
   573  	SetBytes([]byte) (T, error)
   574  	Add(T, T) T
   575  	ScalarMult(T, []byte) (T, error)
   576  	ScalarBaseMult([]byte) (T, error)
   577  }
   578  
   579  // pointFromAffine is used to convert the PublicKey to a nistec Point.
   580  func (curve *nistCurve[Point]) pointFromAffine(x, y *big.Int) (p Point, err error) {
   581  	bitSize := curve.curve.Params().BitSize
   582  	// Reject values that would not get correctly encoded.
   583  	if x.Sign() < 0 || y.Sign() < 0 {
   584  		return p, errors.New("negative coordinate")
   585  	}
   586  	if x.BitLen() > bitSize || y.BitLen() > bitSize {
   587  		return p, errors.New("overflowing coordinate")
   588  	}
   589  	// Encode the coordinates and let SetBytes reject invalid points.
   590  	byteLen := (bitSize + 7) / 8
   591  	buf := make([]byte, 1+2*byteLen)
   592  	buf[0] = 4 // uncompressed point
   593  	x.FillBytes(buf[1 : 1+byteLen])
   594  	y.FillBytes(buf[1+byteLen : 1+2*byteLen])
   595  	return curve.newPoint().SetBytes(buf)
   596  }
   597  
   598  // pointToAffine is used to convert a nistec Point to a PublicKey.
   599  func (curve *nistCurve[Point]) pointToAffine(p Point) (x, y *big.Int, err error) {
   600  	out := p.Bytes()
   601  	if len(out) == 1 && out[0] == 0 {
   602  		// This is the encoding of the point at infinity.
   603  		return nil, nil, errors.New("ecdsa: public key point is the infinity")
   604  	}
   605  	byteLen := (curve.curve.Params().BitSize + 7) / 8
   606  	x = new(big.Int).SetBytes(out[1 : 1+byteLen])
   607  	y = new(big.Int).SetBytes(out[1+byteLen:])
   608  	return x, y, nil
   609  }
   610  
   611  var p224Once sync.Once
   612  var _p224 *nistCurve[*nistec.P224Point]
   613  
   614  func p224() *nistCurve[*nistec.P224Point] {
   615  	p224Once.Do(func() {
   616  		_p224 = &nistCurve[*nistec.P224Point]{
   617  			newPoint: func() *nistec.P224Point { return nistec.NewP224Point() },
   618  		}
   619  		precomputeParams(_p224, elliptic.P224())
   620  	})
   621  	return _p224
   622  }
   623  
   624  var p256Once sync.Once
   625  var _p256 *nistCurve[*nistec.P256Point]
   626  
   627  func p256() *nistCurve[*nistec.P256Point] {
   628  	p256Once.Do(func() {
   629  		_p256 = &nistCurve[*nistec.P256Point]{
   630  			newPoint: func() *nistec.P256Point { return nistec.NewP256Point() },
   631  		}
   632  		precomputeParams(_p256, elliptic.P256())
   633  	})
   634  	return _p256
   635  }
   636  
   637  var p384Once sync.Once
   638  var _p384 *nistCurve[*nistec.P384Point]
   639  
   640  func p384() *nistCurve[*nistec.P384Point] {
   641  	p384Once.Do(func() {
   642  		_p384 = &nistCurve[*nistec.P384Point]{
   643  			newPoint: func() *nistec.P384Point { return nistec.NewP384Point() },
   644  		}
   645  		precomputeParams(_p384, elliptic.P384())
   646  	})
   647  	return _p384
   648  }
   649  
   650  var p521Once sync.Once
   651  var _p521 *nistCurve[*nistec.P521Point]
   652  
   653  func p521() *nistCurve[*nistec.P521Point] {
   654  	p521Once.Do(func() {
   655  		_p521 = &nistCurve[*nistec.P521Point]{
   656  			newPoint: func() *nistec.P521Point { return nistec.NewP521Point() },
   657  		}
   658  		precomputeParams(_p521, elliptic.P521())
   659  	})
   660  	return _p521
   661  }
   662  
   663  func precomputeParams[Point nistPoint[Point]](c *nistCurve[Point], curve elliptic.Curve) {
   664  	params := curve.Params()
   665  	c.curve = curve
   666  	var err error
   667  	c.N, err = bigmod.NewModulusFromBig(params.N)
   668  	if err != nil {
   669  		panic(err)
   670  	}
   671  	c.nMinus2 = new(big.Int).Sub(params.N, big.NewInt(2)).Bytes()
   672  }
   673  

View as plain text