Source file src/crypto/ecdsa/ecdsa_legacy.go

     1  // Copyright 2022 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
     6  
     7  import (
     8  	"crypto/elliptic"
     9  	"crypto/internal/fips140only"
    10  	"errors"
    11  	"io"
    12  	"math/big"
    13  	"math/rand/v2"
    14  
    15  	"golang.org/x/crypto/cryptobyte"
    16  	"golang.org/x/crypto/cryptobyte/asn1"
    17  )
    18  
    19  // This file contains a math/big implementation of ECDSA that is only used for
    20  // deprecated custom curves.
    21  
    22  func generateLegacy(c elliptic.Curve, rand io.Reader) (*PrivateKey, error) {
    23  	if fips140only.Enforced() {
    24  		return nil, errors.New("crypto/ecdsa: use of custom curves is not allowed in FIPS 140-only mode")
    25  	}
    26  
    27  	k, err := randFieldElement(c, rand)
    28  	if err != nil {
    29  		return nil, err
    30  	}
    31  
    32  	priv := new(PrivateKey)
    33  	priv.PublicKey.Curve = c
    34  	priv.D = k
    35  	priv.PublicKey.X, priv.PublicKey.Y = c.ScalarBaseMult(k.Bytes())
    36  	return priv, nil
    37  }
    38  
    39  // hashToInt converts a hash value to an integer. Per FIPS 186-4, Section 6.4,
    40  // we use the left-most bits of the hash to match the bit-length of the order of
    41  // the curve. This also performs Step 5 of SEC 1, Version 2.0, Section 4.1.3.
    42  func hashToInt(hash []byte, c elliptic.Curve) *big.Int {
    43  	orderBits := c.Params().N.BitLen()
    44  	orderBytes := (orderBits + 7) / 8
    45  	if len(hash) > orderBytes {
    46  		hash = hash[:orderBytes]
    47  	}
    48  
    49  	ret := new(big.Int).SetBytes(hash)
    50  	excess := len(hash)*8 - orderBits
    51  	if excess > 0 {
    52  		ret.Rsh(ret, uint(excess))
    53  	}
    54  	return ret
    55  }
    56  
    57  var errZeroParam = errors.New("zero parameter")
    58  
    59  // Sign signs a hash (which should be the result of hashing a larger message)
    60  // using the private key, priv. If the hash is longer than the bit-length of the
    61  // private key's curve order, the hash will be truncated to that length. It
    62  // returns the signature as a pair of integers. Most applications should use
    63  // [SignASN1] instead of dealing directly with r, s.
    64  //
    65  // The signature is randomized. Since Go 1.26, a secure source of random bytes
    66  // is always used, and the Reader is ignored unless GODEBUG=cryptocustomrand=1
    67  // is set. This setting will be removed in a future Go release. Instead, use
    68  // [testing/cryptotest.SetGlobalRandom].
    69  func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error) {
    70  	sig, err := SignASN1(rand, priv, hash)
    71  	if err != nil {
    72  		return nil, nil, err
    73  	}
    74  
    75  	r, s = new(big.Int), new(big.Int)
    76  	var inner cryptobyte.String
    77  	input := cryptobyte.String(sig)
    78  	if !input.ReadASN1(&inner, asn1.SEQUENCE) ||
    79  		!input.Empty() ||
    80  		!inner.ReadASN1Integer(r) ||
    81  		!inner.ReadASN1Integer(s) ||
    82  		!inner.Empty() {
    83  		return nil, nil, errors.New("invalid ASN.1 from SignASN1")
    84  	}
    85  	return r, s, nil
    86  }
    87  
    88  func signLegacy(priv *PrivateKey, csprng io.Reader, hash []byte) (sig []byte, err error) {
    89  	if fips140only.Enforced() {
    90  		return nil, errors.New("crypto/ecdsa: use of custom curves is not allowed in FIPS 140-only mode")
    91  	}
    92  
    93  	c := priv.Curve
    94  
    95  	// A cheap version of hedged signatures, for the deprecated path.
    96  	var seed [32]byte
    97  	if _, err := io.ReadFull(csprng, seed[:]); err != nil {
    98  		return nil, err
    99  	}
   100  	for i, b := range priv.D.Bytes() {
   101  		seed[i%32] ^= b
   102  	}
   103  	for i, b := range hash {
   104  		seed[i%32] ^= b
   105  	}
   106  	csprng = rand.NewChaCha8(seed)
   107  
   108  	// SEC 1, Version 2.0, Section 4.1.3
   109  	N := c.Params().N
   110  	if N.Sign() == 0 {
   111  		return nil, errZeroParam
   112  	}
   113  	var k, kInv, r, s *big.Int
   114  	for {
   115  		for {
   116  			k, err = randFieldElement(c, csprng)
   117  			if err != nil {
   118  				return nil, err
   119  			}
   120  
   121  			kInv = new(big.Int).ModInverse(k, N)
   122  
   123  			r, _ = c.ScalarBaseMult(k.Bytes())
   124  			r.Mod(r, N)
   125  			if r.Sign() != 0 {
   126  				break
   127  			}
   128  		}
   129  
   130  		e := hashToInt(hash, c)
   131  		s = new(big.Int).Mul(priv.D, r)
   132  		s.Add(s, e)
   133  		s.Mul(s, kInv)
   134  		s.Mod(s, N) // N != 0
   135  		if s.Sign() != 0 {
   136  			break
   137  		}
   138  	}
   139  
   140  	return encodeSignature(r.Bytes(), s.Bytes())
   141  }
   142  
   143  // Verify verifies the signature in r, s of hash using the public key, pub. Its
   144  // return value records whether the signature is valid. Most applications should
   145  // use VerifyASN1 instead of dealing directly with r, s.
   146  //
   147  // The inputs are not considered confidential, and may leak through timing side
   148  // channels, or if an attacker has control of part of the inputs.
   149  func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool {
   150  	if r.Sign() <= 0 || s.Sign() <= 0 {
   151  		return false
   152  	}
   153  	sig, err := encodeSignature(r.Bytes(), s.Bytes())
   154  	if err != nil {
   155  		return false
   156  	}
   157  	return VerifyASN1(pub, hash, sig)
   158  }
   159  
   160  func verifyLegacy(pub *PublicKey, hash []byte, sig []byte) bool {
   161  	if fips140only.Enforced() {
   162  		panic("crypto/ecdsa: use of custom curves is not allowed in FIPS 140-only mode")
   163  	}
   164  
   165  	rBytes, sBytes, err := parseSignature(sig)
   166  	if err != nil {
   167  		return false
   168  	}
   169  	r, s := new(big.Int).SetBytes(rBytes), new(big.Int).SetBytes(sBytes)
   170  
   171  	c := pub.Curve
   172  	N := c.Params().N
   173  
   174  	if r.Sign() <= 0 || s.Sign() <= 0 {
   175  		return false
   176  	}
   177  	if r.Cmp(N) >= 0 || s.Cmp(N) >= 0 {
   178  		return false
   179  	}
   180  
   181  	// SEC 1, Version 2.0, Section 4.1.4
   182  	e := hashToInt(hash, c)
   183  	w := new(big.Int).ModInverse(s, N)
   184  
   185  	u1 := e.Mul(e, w)
   186  	u1.Mod(u1, N)
   187  	u2 := w.Mul(r, w)
   188  	u2.Mod(u2, N)
   189  
   190  	x1, y1 := c.ScalarBaseMult(u1.Bytes())
   191  	x2, y2 := c.ScalarMult(pub.X, pub.Y, u2.Bytes())
   192  	x, y := c.Add(x1, y1, x2, y2)
   193  
   194  	if x.Sign() == 0 && y.Sign() == 0 {
   195  		return false
   196  	}
   197  	x.Mod(x, N)
   198  	return x.Cmp(r) == 0
   199  }
   200  
   201  var one = new(big.Int).SetInt64(1)
   202  
   203  // randFieldElement returns a random element of the order of the given
   204  // curve using the procedure given in FIPS 186-4, Appendix B.5.2.
   205  func randFieldElement(c elliptic.Curve, rand io.Reader) (k *big.Int, err error) {
   206  	for {
   207  		N := c.Params().N
   208  		b := make([]byte, (N.BitLen()+7)/8)
   209  		if _, err = io.ReadFull(rand, b); err != nil {
   210  			return
   211  		}
   212  		if excess := len(b)*8 - N.BitLen(); excess > 0 {
   213  			b[0] >>= excess
   214  		}
   215  		k = new(big.Int).SetBytes(b)
   216  		if k.Sign() != 0 && k.Cmp(N) < 0 {
   217  			return
   218  		}
   219  	}
   220  }
   221  

View as plain text