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