Debian Codegraph @

libgo/go/crypto/ecdsa/ecdsa.go

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