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