Source file src/crypto/ecdsa/ecdsa.go

Documentation: crypto/ecdsa

     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-3.
     7  //
     8  // This implementation  derives the nonce from an AES-CTR CSPRNG keyed by
     9  // ChopMD(256, SHA2-512(priv.D || entropy || hash)). The CSPRNG key is IRO by
    10  // a result of Coron; the AES-CTR stream is IRO under standard assumptions.
    11  package ecdsa
    12  
    13  // References:
    14  //   [NSA]: Suite B implementer's guide to FIPS 186-3,
    15  //     https://apps.nsa.gov/iaarchive/library/ia-guidance/ia-solutions-for-classified/algorithm-guidance/suite-b-implementers-guide-to-fips-186-3-ecdsa.cfm
    16  //   [SECG]: SECG, SEC1
    17  //     http://www.secg.org/sec1-v2.pdf
    18  
    19  import (
    20  	"crypto"
    21  	"crypto/aes"
    22  	"crypto/cipher"
    23  	"crypto/elliptic"
    24  	"crypto/internal/randutil"
    25  	"crypto/sha512"
    26  	"encoding/asn1"
    27  	"errors"
    28  	"io"
    29  	"math/big"
    30  )
    31  
    32  // A invertible implements fast inverse mod Curve.Params().N
    33  type invertible interface {
    34  	// Inverse returns the inverse of k in GF(P)
    35  	Inverse(k *big.Int) *big.Int
    36  }
    37  
    38  // combinedMult implements fast multiplication S1*g + S2*p (g - generator, p - arbitrary point)
    39  type combinedMult interface {
    40  	CombinedMult(bigX, bigY *big.Int, baseScalar, scalar []byte) (x, y *big.Int)
    41  }
    42  
    43  const (
    44  	aesIV = "IV for ECDSA CTR"
    45  )
    46  
    47  // PublicKey represents an ECDSA public key.
    48  type PublicKey struct {
    49  	elliptic.Curve
    50  	X, Y *big.Int
    51  }
    52  
    53  // PrivateKey represents an ECDSA private key.
    54  type PrivateKey struct {
    55  	PublicKey
    56  	D *big.Int
    57  }
    58  
    59  type ecdsaSignature struct {
    60  	R, S *big.Int
    61  }
    62  
    63  // Public returns the public key corresponding to priv.
    64  func (priv *PrivateKey) Public() crypto.PublicKey {
    65  	return &priv.PublicKey
    66  }
    67  
    68  // Sign signs digest with priv, reading randomness from rand. The opts argument
    69  // is not currently used but, in keeping with the crypto.Signer interface,
    70  // should be the hash function used to digest the message.
    71  //
    72  // This method implements crypto.Signer, which is an interface to support keys
    73  // where the private part is kept in, for example, a hardware module. Common
    74  // uses should use the Sign function in this package directly.
    75  func (priv *PrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
    76  	r, s, err := Sign(rand, priv, digest)
    77  	if err != nil {
    78  		return nil, err
    79  	}
    80  
    81  	return asn1.Marshal(ecdsaSignature{r, s})
    82  }
    83  
    84  var one = new(big.Int).SetInt64(1)
    85  
    86  // randFieldElement returns a random element of the field underlying the given
    87  // curve using the procedure given in [NSA] A.2.1.
    88  func randFieldElement(c elliptic.Curve, rand io.Reader) (k *big.Int, err error) {
    89  	params := c.Params()
    90  	b := make([]byte, params.BitSize/8+8)
    91  	_, err = io.ReadFull(rand, b)
    92  	if err != nil {
    93  		return
    94  	}
    95  
    96  	k = new(big.Int).SetBytes(b)
    97  	n := new(big.Int).Sub(params.N, one)
    98  	k.Mod(k, n)
    99  	k.Add(k, one)
   100  	return
   101  }
   102  
   103  // GenerateKey generates a public and private key pair.
   104  func GenerateKey(c elliptic.Curve, rand io.Reader) (*PrivateKey, error) {
   105  	k, err := randFieldElement(c, rand)
   106  	if err != nil {
   107  		return nil, err
   108  	}
   109  
   110  	priv := new(PrivateKey)
   111  	priv.PublicKey.Curve = c
   112  	priv.D = k
   113  	priv.PublicKey.X, priv.PublicKey.Y = c.ScalarBaseMult(k.Bytes())
   114  	return priv, nil
   115  }
   116  
   117  // hashToInt converts a hash value to an integer. There is some disagreement
   118  // about how this is done. [NSA] suggests that this is done in the obvious
   119  // manner, but [SECG] truncates the hash to the bit-length of the curve order
   120  // first. We follow [SECG] because that's what OpenSSL does. Additionally,
   121  // OpenSSL right shifts excess bits from the number if the hash is too large
   122  // and we mirror that too.
   123  func hashToInt(hash []byte, c elliptic.Curve) *big.Int {
   124  	orderBits := c.Params().N.BitLen()
   125  	orderBytes := (orderBits + 7) / 8
   126  	if len(hash) > orderBytes {
   127  		hash = hash[:orderBytes]
   128  	}
   129  
   130  	ret := new(big.Int).SetBytes(hash)
   131  	excess := len(hash)*8 - orderBits
   132  	if excess > 0 {
   133  		ret.Rsh(ret, uint(excess))
   134  	}
   135  	return ret
   136  }
   137  
   138  // fermatInverse calculates the inverse of k in GF(P) using Fermat's method.
   139  // This has better constant-time properties than Euclid's method (implemented
   140  // in math/big.Int.ModInverse) although math/big itself isn't strictly
   141  // constant-time so it's not perfect.
   142  func fermatInverse(k, N *big.Int) *big.Int {
   143  	two := big.NewInt(2)
   144  	nMinus2 := new(big.Int).Sub(N, two)
   145  	return new(big.Int).Exp(k, nMinus2, N)
   146  }
   147  
   148  var errZeroParam = errors.New("zero parameter")
   149  
   150  // Sign signs a hash (which should be the result of hashing a larger message)
   151  // using the private key, priv. If the hash is longer than the bit-length of the
   152  // private key's curve order, the hash will be truncated to that length.  It
   153  // returns the signature as a pair of integers. The security of the private key
   154  // depends on the entropy of rand.
   155  func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error) {
   156  	randutil.MaybeReadByte(rand)
   157  
   158  	// Get min(log2(q) / 2, 256) bits of entropy from rand.
   159  	entropylen := (priv.Curve.Params().BitSize + 7) / 16
   160  	if entropylen > 32 {
   161  		entropylen = 32
   162  	}
   163  	entropy := make([]byte, entropylen)
   164  	_, err = io.ReadFull(rand, entropy)
   165  	if err != nil {
   166  		return
   167  	}
   168  
   169  	// Initialize an SHA-512 hash context; digest ...
   170  	md := sha512.New()
   171  	md.Write(priv.D.Bytes()) // the private key,
   172  	md.Write(entropy)        // the entropy,
   173  	md.Write(hash)           // and the input hash;
   174  	key := md.Sum(nil)[:32]  // and compute ChopMD-256(SHA-512),
   175  	// which is an indifferentiable MAC.
   176  
   177  	// Create an AES-CTR instance to use as a CSPRNG.
   178  	block, err := aes.NewCipher(key)
   179  	if err != nil {
   180  		return nil, nil, err
   181  	}
   182  
   183  	// Create a CSPRNG that xors a stream of zeros with
   184  	// the output of the AES-CTR instance.
   185  	csprng := cipher.StreamReader{
   186  		R: zeroReader,
   187  		S: cipher.NewCTR(block, []byte(aesIV)),
   188  	}
   189  
   190  	// See [NSA] 3.4.1
   191  	c := priv.PublicKey.Curve
   192  	e := hashToInt(hash, c)
   193  	r, s, err = sign(priv, &csprng, c, e)
   194  	return
   195  }
   196  
   197  func signGeneric(priv *PrivateKey, csprng *cipher.StreamReader, c elliptic.Curve, e *big.Int) (r, s *big.Int, err error) {
   198  	N := c.Params().N
   199  	if N.Sign() == 0 {
   200  		return nil, nil, errZeroParam
   201  	}
   202  
   203  	var k, kInv *big.Int
   204  	for {
   205  		for {
   206  			k, err = randFieldElement(c, *csprng)
   207  			if err != nil {
   208  				r = nil
   209  				return
   210  			}
   211  
   212  			if in, ok := priv.Curve.(invertible); ok {
   213  				kInv = in.Inverse(k)
   214  			} else {
   215  				kInv = fermatInverse(k, N) // N != 0
   216  			}
   217  
   218  			r, _ = priv.Curve.ScalarBaseMult(k.Bytes())
   219  			r.Mod(r, N)
   220  			if r.Sign() != 0 {
   221  				break
   222  			}
   223  		}
   224  		s = new(big.Int).Mul(priv.D, r)
   225  		s.Add(s, e)
   226  		s.Mul(s, kInv)
   227  		s.Mod(s, N) // N != 0
   228  		if s.Sign() != 0 {
   229  			break
   230  		}
   231  	}
   232  	return
   233  }
   234  
   235  // Verify verifies the signature in r, s of hash using the public key, pub. Its
   236  // return value records whether the signature is valid.
   237  func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool {
   238  	// See [NSA] 3.4.2
   239  	c := pub.Curve
   240  	N := c.Params().N
   241  
   242  	if r.Sign() <= 0 || s.Sign() <= 0 {
   243  		return false
   244  	}
   245  	if r.Cmp(N) >= 0 || s.Cmp(N) >= 0 {
   246  		return false
   247  	}
   248  	e := hashToInt(hash, c)
   249  	return verify(pub, c, e, r, s)
   250  }
   251  
   252  func verifyGeneric(pub *PublicKey, c elliptic.Curve, e, r, s *big.Int) bool {
   253  	var w *big.Int
   254  	N := c.Params().N
   255  	if in, ok := c.(invertible); ok {
   256  		w = in.Inverse(s)
   257  	} else {
   258  		w = new(big.Int).ModInverse(s, N)
   259  	}
   260  
   261  	u1 := e.Mul(e, w)
   262  	u1.Mod(u1, N)
   263  	u2 := w.Mul(r, w)
   264  	u2.Mod(u2, N)
   265  
   266  	// Check if implements S1*g + S2*p
   267  	var x, y *big.Int
   268  	if opt, ok := c.(combinedMult); ok {
   269  		x, y = opt.CombinedMult(pub.X, pub.Y, u1.Bytes(), u2.Bytes())
   270  	} else {
   271  		x1, y1 := c.ScalarBaseMult(u1.Bytes())
   272  		x2, y2 := c.ScalarMult(pub.X, pub.Y, u2.Bytes())
   273  		x, y = c.Add(x1, y1, x2, y2)
   274  	}
   275  
   276  	if x.Sign() == 0 && y.Sign() == 0 {
   277  		return false
   278  	}
   279  	x.Mod(x, N)
   280  	return x.Cmp(r) == 0
   281  }
   282  
   283  type zr struct {
   284  	io.Reader
   285  }
   286  
   287  // Read replaces the contents of dst with zeros.
   288  func (z *zr) Read(dst []byte) (n int, err error) {
   289  	for i := range dst {
   290  		dst[i] = 0
   291  	}
   292  	return len(dst), nil
   293  }
   294  
   295  var zeroReader = &zr{}
   296  

View as plain text