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