1
2
3
4
5
6
7
8
9
10
11 package ecdsa
12
13
14
15
16
17
18
19
20
21
22 import (
23 "bytes"
24 "crypto"
25 "crypto/aes"
26 "crypto/cipher"
27 "crypto/ecdh"
28 "crypto/elliptic"
29 "crypto/internal/bigmod"
30 "crypto/internal/boring"
31 "crypto/internal/boring/bbig"
32 "crypto/internal/nistec"
33 "crypto/internal/randutil"
34 "crypto/sha512"
35 "crypto/subtle"
36 "errors"
37 "io"
38 "math/big"
39 "sync"
40
41 "golang.org/x/crypto/cryptobyte"
42 "golang.org/x/crypto/cryptobyte/asn1"
43 )
44
45
46 type PublicKey struct {
47 elliptic.Curve
48 X, Y *big.Int
49 }
50
51
52
53
54
55
56
57 func (k *PublicKey) ECDH() (*ecdh.PublicKey, error) {
58 c := curveToECDH(k.Curve)
59 if c == nil {
60 return nil, errors.New("ecdsa: unsupported curve by crypto/ecdh")
61 }
62 if !k.Curve.IsOnCurve(k.X, k.Y) {
63 return nil, errors.New("ecdsa: invalid public key")
64 }
65 return c.NewPublicKey(elliptic.Marshal(k.Curve, k.X, k.Y))
66 }
67
68
69
70
71
72
73 func (pub *PublicKey) Equal(x crypto.PublicKey) bool {
74 xx, ok := x.(*PublicKey)
75 if !ok {
76 return false
77 }
78 return bigIntEqual(pub.X, xx.X) && bigIntEqual(pub.Y, xx.Y) &&
79
80
81
82
83 pub.Curve == xx.Curve
84 }
85
86
87 type PrivateKey struct {
88 PublicKey
89 D *big.Int
90 }
91
92
93
94
95 func (k *PrivateKey) ECDH() (*ecdh.PrivateKey, error) {
96 c := curveToECDH(k.Curve)
97 if c == nil {
98 return nil, errors.New("ecdsa: unsupported curve by crypto/ecdh")
99 }
100 size := (k.Curve.Params().N.BitLen() + 7) / 8
101 if k.D.BitLen() > size*8 {
102 return nil, errors.New("ecdsa: invalid private key")
103 }
104 return c.NewPrivateKey(k.D.FillBytes(make([]byte, size)))
105 }
106
107 func curveToECDH(c elliptic.Curve) ecdh.Curve {
108 switch c {
109 case elliptic.P256():
110 return ecdh.P256()
111 case elliptic.P384():
112 return ecdh.P384()
113 case elliptic.P521():
114 return ecdh.P521()
115 default:
116 return nil
117 }
118 }
119
120
121 func (priv *PrivateKey) Public() crypto.PublicKey {
122 return &priv.PublicKey
123 }
124
125
126
127
128 func (priv *PrivateKey) Equal(x crypto.PrivateKey) bool {
129 xx, ok := x.(*PrivateKey)
130 if !ok {
131 return false
132 }
133 return priv.PublicKey.Equal(&xx.PublicKey) && bigIntEqual(priv.D, xx.D)
134 }
135
136
137
138 func bigIntEqual(a, b *big.Int) bool {
139 return subtle.ConstantTimeCompare(a.Bytes(), b.Bytes()) == 1
140 }
141
142
143
144
145
146
147
148
149 func (priv *PrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
150 return SignASN1(rand, priv, digest)
151 }
152
153
154 func GenerateKey(c elliptic.Curve, rand io.Reader) (*PrivateKey, error) {
155 randutil.MaybeReadByte(rand)
156
157 if boring.Enabled && rand == boring.RandReader {
158 x, y, d, err := boring.GenerateKeyECDSA(c.Params().Name)
159 if err != nil {
160 return nil, err
161 }
162 return &PrivateKey{PublicKey: PublicKey{Curve: c, X: bbig.Dec(x), Y: bbig.Dec(y)}, D: bbig.Dec(d)}, nil
163 }
164 boring.UnreachableExceptTests()
165
166 switch c.Params() {
167 case elliptic.P224().Params():
168 return generateNISTEC(p224(), rand)
169 case elliptic.P256().Params():
170 return generateNISTEC(p256(), rand)
171 case elliptic.P384().Params():
172 return generateNISTEC(p384(), rand)
173 case elliptic.P521().Params():
174 return generateNISTEC(p521(), rand)
175 default:
176 return generateLegacy(c, rand)
177 }
178 }
179
180 func generateNISTEC[Point nistPoint[Point]](c *nistCurve[Point], rand io.Reader) (*PrivateKey, error) {
181 k, Q, err := randomPoint(c, rand)
182 if err != nil {
183 return nil, err
184 }
185
186 priv := new(PrivateKey)
187 priv.PublicKey.Curve = c.curve
188 priv.D = new(big.Int).SetBytes(k.Bytes(c.N))
189 priv.PublicKey.X, priv.PublicKey.Y, err = c.pointToAffine(Q)
190 if err != nil {
191 return nil, err
192 }
193 return priv, nil
194 }
195
196
197
198 func randomPoint[Point nistPoint[Point]](c *nistCurve[Point], rand io.Reader) (k *bigmod.Nat, p Point, err error) {
199 k = bigmod.NewNat()
200 for {
201 b := make([]byte, c.N.Size())
202 if _, err = io.ReadFull(rand, b); err != nil {
203 return
204 }
205
206
207
208
209
210 if excess := len(b)*8 - c.N.BitLen(); excess > 0 {
211
212
213 if excess != 0 && c.curve.Params().Name != "P-521" {
214 panic("ecdsa: internal error: unexpectedly masking off bits")
215 }
216 b[0] >>= excess
217 }
218
219
220
221
222
223 if _, err = k.SetBytes(b, c.N); err == nil && k.IsZero() == 0 {
224 break
225 }
226
227 if testingOnlyRejectionSamplingLooped != nil {
228 testingOnlyRejectionSamplingLooped()
229 }
230 }
231
232 p, err = c.newPoint().ScalarBaseMult(k.Bytes(c.N))
233 return
234 }
235
236
237
238 var testingOnlyRejectionSamplingLooped func()
239
240
241
242 var errNoAsm = errors.New("no assembly implementation available")
243
244
245
246
247
248 func SignASN1(rand io.Reader, priv *PrivateKey, hash []byte) ([]byte, error) {
249 randutil.MaybeReadByte(rand)
250
251 if boring.Enabled && rand == boring.RandReader {
252 b, err := boringPrivateKey(priv)
253 if err != nil {
254 return nil, err
255 }
256 return boring.SignMarshalECDSA(b, hash)
257 }
258 boring.UnreachableExceptTests()
259
260 csprng, err := mixedCSPRNG(rand, priv, hash)
261 if err != nil {
262 return nil, err
263 }
264
265 if sig, err := signAsm(priv, csprng, hash); err != errNoAsm {
266 return sig, err
267 }
268
269 switch priv.Curve.Params() {
270 case elliptic.P224().Params():
271 return signNISTEC(p224(), priv, csprng, hash)
272 case elliptic.P256().Params():
273 return signNISTEC(p256(), priv, csprng, hash)
274 case elliptic.P384().Params():
275 return signNISTEC(p384(), priv, csprng, hash)
276 case elliptic.P521().Params():
277 return signNISTEC(p521(), priv, csprng, hash)
278 default:
279 return signLegacy(priv, csprng, hash)
280 }
281 }
282
283 func signNISTEC[Point nistPoint[Point]](c *nistCurve[Point], priv *PrivateKey, csprng io.Reader, hash []byte) (sig []byte, err error) {
284
285
286 k, R, err := randomPoint(c, csprng)
287 if err != nil {
288 return nil, err
289 }
290
291
292 kInv := bigmod.NewNat()
293 inverse(c, kInv, k)
294
295 Rx, err := R.BytesX()
296 if err != nil {
297 return nil, err
298 }
299 r, err := bigmod.NewNat().SetOverflowingBytes(Rx, c.N)
300 if err != nil {
301 return nil, err
302 }
303
304
305
306
307 if r.IsZero() == 1 {
308 return nil, errors.New("ecdsa: internal error: r is zero")
309 }
310
311 e := bigmod.NewNat()
312 hashToNat(c, e, hash)
313
314 s, err := bigmod.NewNat().SetBytes(priv.D.Bytes(), c.N)
315 if err != nil {
316 return nil, err
317 }
318 s.Mul(r, c.N)
319 s.Add(e, c.N)
320 s.Mul(kInv, c.N)
321
322
323 if s.IsZero() == 1 {
324 return nil, errors.New("ecdsa: internal error: s is zero")
325 }
326
327 return encodeSignature(r.Bytes(c.N), s.Bytes(c.N))
328 }
329
330 func encodeSignature(r, s []byte) ([]byte, error) {
331 var b cryptobyte.Builder
332 b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
333 addASN1IntBytes(b, r)
334 addASN1IntBytes(b, s)
335 })
336 return b.Bytes()
337 }
338
339
340
341 func addASN1IntBytes(b *cryptobyte.Builder, bytes []byte) {
342 for len(bytes) > 0 && bytes[0] == 0 {
343 bytes = bytes[1:]
344 }
345 if len(bytes) == 0 {
346 b.SetError(errors.New("invalid integer"))
347 return
348 }
349 b.AddASN1(asn1.INTEGER, func(c *cryptobyte.Builder) {
350 if bytes[0]&0x80 != 0 {
351 c.AddUint8(0)
352 }
353 c.AddBytes(bytes)
354 })
355 }
356
357
358 func inverse[Point nistPoint[Point]](c *nistCurve[Point], kInv, k *bigmod.Nat) {
359 if c.curve.Params().Name == "P-256" {
360 kBytes, err := nistec.P256OrdInverse(k.Bytes(c.N))
361
362 if err == nil {
363 _, err := kInv.SetBytes(kBytes, c.N)
364 if err != nil {
365 panic("ecdsa: internal error: P256OrdInverse produced an invalid value")
366 }
367 return
368 }
369 }
370
371
372
373 kInv.Exp(k, c.nMinus2, c.N)
374 }
375
376
377
378 func hashToNat[Point nistPoint[Point]](c *nistCurve[Point], e *bigmod.Nat, hash []byte) {
379
380
381
382
383 if size := c.N.Size(); len(hash) > size {
384 hash = hash[:size]
385 if excess := len(hash)*8 - c.N.BitLen(); excess > 0 {
386 hash = bytes.Clone(hash)
387 for i := len(hash) - 1; i >= 0; i-- {
388 hash[i] >>= excess
389 if i > 0 {
390 hash[i] |= hash[i-1] << (8 - excess)
391 }
392 }
393 }
394 }
395 _, err := e.SetOverflowingBytes(hash, c.N)
396 if err != nil {
397 panic("ecdsa: internal error: truncated hash is too long")
398 }
399 }
400
401
402
403
404
405 func mixedCSPRNG(rand io.Reader, priv *PrivateKey, hash []byte) (io.Reader, error) {
406
407
408
409
410
411
412
413
414
415
416
417
418 entropy := make([]byte, 32)
419 if _, err := io.ReadFull(rand, entropy); err != nil {
420 return nil, err
421 }
422
423
424 md := sha512.New()
425 md.Write(priv.D.Bytes())
426 md.Write(entropy)
427 md.Write(hash)
428 key := md.Sum(nil)[:32]
429
430
431
432 block, err := aes.NewCipher(key)
433 if err != nil {
434 return nil, err
435 }
436
437
438
439 const aesIV = "IV for ECDSA CTR"
440 return &cipher.StreamReader{
441 R: zeroReader,
442 S: cipher.NewCTR(block, []byte(aesIV)),
443 }, nil
444 }
445
446 type zr struct{}
447
448 var zeroReader = zr{}
449
450
451 func (zr) Read(dst []byte) (n int, err error) {
452 for i := range dst {
453 dst[i] = 0
454 }
455 return len(dst), nil
456 }
457
458
459
460 func VerifyASN1(pub *PublicKey, hash, sig []byte) bool {
461 if boring.Enabled {
462 key, err := boringPublicKey(pub)
463 if err != nil {
464 return false
465 }
466 return boring.VerifyECDSA(key, hash, sig)
467 }
468 boring.UnreachableExceptTests()
469
470 if err := verifyAsm(pub, hash, sig); err != errNoAsm {
471 return err == nil
472 }
473
474 switch pub.Curve.Params() {
475 case elliptic.P224().Params():
476 return verifyNISTEC(p224(), pub, hash, sig)
477 case elliptic.P256().Params():
478 return verifyNISTEC(p256(), pub, hash, sig)
479 case elliptic.P384().Params():
480 return verifyNISTEC(p384(), pub, hash, sig)
481 case elliptic.P521().Params():
482 return verifyNISTEC(p521(), pub, hash, sig)
483 default:
484 return verifyLegacy(pub, hash, sig)
485 }
486 }
487
488 func verifyNISTEC[Point nistPoint[Point]](c *nistCurve[Point], pub *PublicKey, hash, sig []byte) bool {
489 rBytes, sBytes, err := parseSignature(sig)
490 if err != nil {
491 return false
492 }
493
494 Q, err := c.pointFromAffine(pub.X, pub.Y)
495 if err != nil {
496 return false
497 }
498
499
500
501 r, err := bigmod.NewNat().SetBytes(rBytes, c.N)
502 if err != nil || r.IsZero() == 1 {
503 return false
504 }
505 s, err := bigmod.NewNat().SetBytes(sBytes, c.N)
506 if err != nil || s.IsZero() == 1 {
507 return false
508 }
509
510 e := bigmod.NewNat()
511 hashToNat(c, e, hash)
512
513
514 w := bigmod.NewNat()
515 inverse(c, w, s)
516
517
518 p1, err := c.newPoint().ScalarBaseMult(e.Mul(w, c.N).Bytes(c.N))
519 if err != nil {
520 return false
521 }
522
523 p2, err := Q.ScalarMult(Q, w.Mul(r, c.N).Bytes(c.N))
524 if err != nil {
525 return false
526 }
527
528 Rx, err := p1.Add(p1, p2).BytesX()
529 if err != nil {
530 return false
531 }
532
533 v, err := bigmod.NewNat().SetOverflowingBytes(Rx, c.N)
534 if err != nil {
535 return false
536 }
537
538 return v.Equal(r) == 1
539 }
540
541 func parseSignature(sig []byte) (r, s []byte, err error) {
542 var inner cryptobyte.String
543 input := cryptobyte.String(sig)
544 if !input.ReadASN1(&inner, asn1.SEQUENCE) ||
545 !input.Empty() ||
546 !inner.ReadASN1Integer(&r) ||
547 !inner.ReadASN1Integer(&s) ||
548 !inner.Empty() {
549 return nil, nil, errors.New("invalid ASN.1")
550 }
551 return r, s, nil
552 }
553
554 type nistCurve[Point nistPoint[Point]] struct {
555 newPoint func() Point
556 curve elliptic.Curve
557 N *bigmod.Modulus
558 nMinus2 []byte
559 }
560
561
562 type nistPoint[T any] interface {
563 Bytes() []byte
564 BytesX() ([]byte, error)
565 SetBytes([]byte) (T, error)
566 Add(T, T) T
567 ScalarMult(T, []byte) (T, error)
568 ScalarBaseMult([]byte) (T, error)
569 }
570
571
572 func (curve *nistCurve[Point]) pointFromAffine(x, y *big.Int) (p Point, err error) {
573 bitSize := curve.curve.Params().BitSize
574
575 if x.Sign() < 0 || y.Sign() < 0 {
576 return p, errors.New("negative coordinate")
577 }
578 if x.BitLen() > bitSize || y.BitLen() > bitSize {
579 return p, errors.New("overflowing coordinate")
580 }
581
582 byteLen := (bitSize + 7) / 8
583 buf := make([]byte, 1+2*byteLen)
584 buf[0] = 4
585 x.FillBytes(buf[1 : 1+byteLen])
586 y.FillBytes(buf[1+byteLen : 1+2*byteLen])
587 return curve.newPoint().SetBytes(buf)
588 }
589
590
591 func (curve *nistCurve[Point]) pointToAffine(p Point) (x, y *big.Int, err error) {
592 out := p.Bytes()
593 if len(out) == 1 && out[0] == 0 {
594
595 return nil, nil, errors.New("ecdsa: public key point is the infinity")
596 }
597 byteLen := (curve.curve.Params().BitSize + 7) / 8
598 x = new(big.Int).SetBytes(out[1 : 1+byteLen])
599 y = new(big.Int).SetBytes(out[1+byteLen:])
600 return x, y, nil
601 }
602
603 var p224Once sync.Once
604 var _p224 *nistCurve[*nistec.P224Point]
605
606 func p224() *nistCurve[*nistec.P224Point] {
607 p224Once.Do(func() {
608 _p224 = &nistCurve[*nistec.P224Point]{
609 newPoint: func() *nistec.P224Point { return nistec.NewP224Point() },
610 }
611 precomputeParams(_p224, elliptic.P224())
612 })
613 return _p224
614 }
615
616 var p256Once sync.Once
617 var _p256 *nistCurve[*nistec.P256Point]
618
619 func p256() *nistCurve[*nistec.P256Point] {
620 p256Once.Do(func() {
621 _p256 = &nistCurve[*nistec.P256Point]{
622 newPoint: func() *nistec.P256Point { return nistec.NewP256Point() },
623 }
624 precomputeParams(_p256, elliptic.P256())
625 })
626 return _p256
627 }
628
629 var p384Once sync.Once
630 var _p384 *nistCurve[*nistec.P384Point]
631
632 func p384() *nistCurve[*nistec.P384Point] {
633 p384Once.Do(func() {
634 _p384 = &nistCurve[*nistec.P384Point]{
635 newPoint: func() *nistec.P384Point { return nistec.NewP384Point() },
636 }
637 precomputeParams(_p384, elliptic.P384())
638 })
639 return _p384
640 }
641
642 var p521Once sync.Once
643 var _p521 *nistCurve[*nistec.P521Point]
644
645 func p521() *nistCurve[*nistec.P521Point] {
646 p521Once.Do(func() {
647 _p521 = &nistCurve[*nistec.P521Point]{
648 newPoint: func() *nistec.P521Point { return nistec.NewP521Point() },
649 }
650 precomputeParams(_p521, elliptic.P521())
651 })
652 return _p521
653 }
654
655 func precomputeParams[Point nistPoint[Point]](c *nistCurve[Point], curve elliptic.Curve) {
656 params := curve.Params()
657 c.curve = curve
658 c.N = bigmod.NewModulusFromBig(params.N)
659 c.nMinus2 = new(big.Int).Sub(params.N, big.NewInt(2)).Bytes()
660 }
661
View as plain text