1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 package rsa
26
27 import (
28 "crypto"
29 "crypto/internal/bigmod"
30 "crypto/internal/boring"
31 "crypto/internal/boring/bbig"
32 "crypto/internal/randutil"
33 "crypto/rand"
34 "crypto/subtle"
35 "errors"
36 "hash"
37 "io"
38 "math"
39 "math/big"
40 )
41
42 var bigOne = big.NewInt(1)
43
44
45
46
47
48
49 type PublicKey struct {
50 N *big.Int
51 E int
52 }
53
54
55
56
57
58
59 func (pub *PublicKey) Size() int {
60 return (pub.N.BitLen() + 7) / 8
61 }
62
63
64 func (pub *PublicKey) Equal(x crypto.PublicKey) bool {
65 xx, ok := x.(*PublicKey)
66 if !ok {
67 return false
68 }
69 return bigIntEqual(pub.N, xx.N) && pub.E == xx.E
70 }
71
72
73
74 type OAEPOptions struct {
75
76 Hash crypto.Hash
77
78
79
80 MGFHash crypto.Hash
81
82
83
84 Label []byte
85 }
86
87 var (
88 errPublicModulus = errors.New("crypto/rsa: missing public modulus")
89 errPublicExponentSmall = errors.New("crypto/rsa: public exponent too small")
90 errPublicExponentLarge = errors.New("crypto/rsa: public exponent too large")
91 )
92
93
94
95
96
97
98 func checkPub(pub *PublicKey) error {
99 if pub.N == nil {
100 return errPublicModulus
101 }
102 if pub.E < 2 {
103 return errPublicExponentSmall
104 }
105 if pub.E > 1<<31-1 {
106 return errPublicExponentLarge
107 }
108 return nil
109 }
110
111
112 type PrivateKey struct {
113 PublicKey
114 D *big.Int
115 Primes []*big.Int
116
117
118
119
120 Precomputed PrecomputedValues
121 }
122
123
124 func (priv *PrivateKey) Public() crypto.PublicKey {
125 return &priv.PublicKey
126 }
127
128
129
130 func (priv *PrivateKey) Equal(x crypto.PrivateKey) bool {
131 xx, ok := x.(*PrivateKey)
132 if !ok {
133 return false
134 }
135 if !priv.PublicKey.Equal(&xx.PublicKey) || !bigIntEqual(priv.D, xx.D) {
136 return false
137 }
138 if len(priv.Primes) != len(xx.Primes) {
139 return false
140 }
141 for i := range priv.Primes {
142 if !bigIntEqual(priv.Primes[i], xx.Primes[i]) {
143 return false
144 }
145 }
146 return true
147 }
148
149
150
151 func bigIntEqual(a, b *big.Int) bool {
152 return subtle.ConstantTimeCompare(a.Bytes(), b.Bytes()) == 1
153 }
154
155
156
157
158
159
160
161
162
163 func (priv *PrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
164 if pssOpts, ok := opts.(*PSSOptions); ok {
165 return SignPSS(rand, priv, pssOpts.Hash, digest, pssOpts)
166 }
167
168 return SignPKCS1v15(rand, priv, opts.HashFunc(), digest)
169 }
170
171
172
173
174 func (priv *PrivateKey) Decrypt(rand io.Reader, ciphertext []byte, opts crypto.DecrypterOpts) (plaintext []byte, err error) {
175 if opts == nil {
176 return DecryptPKCS1v15(rand, priv, ciphertext)
177 }
178
179 switch opts := opts.(type) {
180 case *OAEPOptions:
181 if opts.MGFHash == 0 {
182 return decryptOAEP(opts.Hash.New(), opts.Hash.New(), rand, priv, ciphertext, opts.Label)
183 } else {
184 return decryptOAEP(opts.Hash.New(), opts.MGFHash.New(), rand, priv, ciphertext, opts.Label)
185 }
186
187 case *PKCS1v15DecryptOptions:
188 if l := opts.SessionKeyLen; l > 0 {
189 plaintext = make([]byte, l)
190 if _, err := io.ReadFull(rand, plaintext); err != nil {
191 return nil, err
192 }
193 if err := DecryptPKCS1v15SessionKey(rand, priv, ciphertext, plaintext); err != nil {
194 return nil, err
195 }
196 return plaintext, nil
197 } else {
198 return DecryptPKCS1v15(rand, priv, ciphertext)
199 }
200
201 default:
202 return nil, errors.New("crypto/rsa: invalid options for Decrypt")
203 }
204 }
205
206 type PrecomputedValues struct {
207 Dp, Dq *big.Int
208 Qinv *big.Int
209
210
211
212
213
214
215
216
217
218
219 CRTValues []CRTValue
220
221 n, p, q *bigmod.Modulus
222 }
223
224
225 type CRTValue struct {
226 Exp *big.Int
227 Coeff *big.Int
228 R *big.Int
229 }
230
231
232
233 func (priv *PrivateKey) Validate() error {
234 if err := checkPub(&priv.PublicKey); err != nil {
235 return err
236 }
237
238
239 modulus := new(big.Int).Set(bigOne)
240 for _, prime := range priv.Primes {
241
242 if prime.Cmp(bigOne) <= 0 {
243 return errors.New("crypto/rsa: invalid prime value")
244 }
245 modulus.Mul(modulus, prime)
246 }
247 if modulus.Cmp(priv.N) != 0 {
248 return errors.New("crypto/rsa: invalid modulus")
249 }
250
251
252
253
254
255
256 congruence := new(big.Int)
257 de := new(big.Int).SetInt64(int64(priv.E))
258 de.Mul(de, priv.D)
259 for _, prime := range priv.Primes {
260 pminus1 := new(big.Int).Sub(prime, bigOne)
261 congruence.Mod(de, pminus1)
262 if congruence.Cmp(bigOne) != 0 {
263 return errors.New("crypto/rsa: invalid exponents")
264 }
265 }
266 return nil
267 }
268
269
270
271
272
273
274 func GenerateKey(random io.Reader, bits int) (*PrivateKey, error) {
275 return GenerateMultiPrimeKey(random, 2, bits)
276 }
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297 func GenerateMultiPrimeKey(random io.Reader, nprimes int, bits int) (*PrivateKey, error) {
298 randutil.MaybeReadByte(random)
299
300 if boring.Enabled && random == boring.RandReader && nprimes == 2 &&
301 (bits == 2048 || bits == 3072 || bits == 4096) {
302 bN, bE, bD, bP, bQ, bDp, bDq, bQinv, err := boring.GenerateKeyRSA(bits)
303 if err != nil {
304 return nil, err
305 }
306 N := bbig.Dec(bN)
307 E := bbig.Dec(bE)
308 D := bbig.Dec(bD)
309 P := bbig.Dec(bP)
310 Q := bbig.Dec(bQ)
311 Dp := bbig.Dec(bDp)
312 Dq := bbig.Dec(bDq)
313 Qinv := bbig.Dec(bQinv)
314 e64 := E.Int64()
315 if !E.IsInt64() || int64(int(e64)) != e64 {
316 return nil, errors.New("crypto/rsa: generated key exponent too large")
317 }
318
319 mn, err := bigmod.NewModulusFromBig(N)
320 if err != nil {
321 return nil, err
322 }
323 mp, err := bigmod.NewModulusFromBig(P)
324 if err != nil {
325 return nil, err
326 }
327 mq, err := bigmod.NewModulusFromBig(Q)
328 if err != nil {
329 return nil, err
330 }
331
332 key := &PrivateKey{
333 PublicKey: PublicKey{
334 N: N,
335 E: int(e64),
336 },
337 D: D,
338 Primes: []*big.Int{P, Q},
339 Precomputed: PrecomputedValues{
340 Dp: Dp,
341 Dq: Dq,
342 Qinv: Qinv,
343 CRTValues: make([]CRTValue, 0),
344 n: mn,
345 p: mp,
346 q: mq,
347 },
348 }
349 return key, nil
350 }
351
352 priv := new(PrivateKey)
353 priv.E = 65537
354
355 if nprimes < 2 {
356 return nil, errors.New("crypto/rsa: GenerateMultiPrimeKey: nprimes must be >= 2")
357 }
358
359 if bits < 64 {
360 primeLimit := float64(uint64(1) << uint(bits/nprimes))
361
362 pi := primeLimit / (math.Log(primeLimit) - 1)
363
364
365 pi /= 4
366
367
368 pi /= 2
369 if pi <= float64(nprimes) {
370 return nil, errors.New("crypto/rsa: too few primes of given length to generate an RSA key")
371 }
372 }
373
374 primes := make([]*big.Int, nprimes)
375
376 NextSetOfPrimes:
377 for {
378 todo := bits
379
380
381
382
383
384
385
386
387
388
389
390 if nprimes >= 7 {
391 todo += (nprimes - 2) / 5
392 }
393 for i := 0; i < nprimes; i++ {
394 var err error
395 primes[i], err = rand.Prime(random, todo/(nprimes-i))
396 if err != nil {
397 return nil, err
398 }
399 todo -= primes[i].BitLen()
400 }
401
402
403 for i, prime := range primes {
404 for j := 0; j < i; j++ {
405 if prime.Cmp(primes[j]) == 0 {
406 continue NextSetOfPrimes
407 }
408 }
409 }
410
411 n := new(big.Int).Set(bigOne)
412 totient := new(big.Int).Set(bigOne)
413 pminus1 := new(big.Int)
414 for _, prime := range primes {
415 n.Mul(n, prime)
416 pminus1.Sub(prime, bigOne)
417 totient.Mul(totient, pminus1)
418 }
419 if n.BitLen() != bits {
420
421
422
423 continue NextSetOfPrimes
424 }
425
426 priv.D = new(big.Int)
427 e := big.NewInt(int64(priv.E))
428 ok := priv.D.ModInverse(e, totient)
429
430 if ok != nil {
431 priv.Primes = primes
432 priv.N = n
433 break
434 }
435 }
436
437 priv.Precompute()
438 return priv, nil
439 }
440
441
442 func incCounter(c *[4]byte) {
443 if c[3]++; c[3] != 0 {
444 return
445 }
446 if c[2]++; c[2] != 0 {
447 return
448 }
449 if c[1]++; c[1] != 0 {
450 return
451 }
452 c[0]++
453 }
454
455
456
457 func mgf1XOR(out []byte, hash hash.Hash, seed []byte) {
458 var counter [4]byte
459 var digest []byte
460
461 done := 0
462 for done < len(out) {
463 hash.Write(seed)
464 hash.Write(counter[0:4])
465 digest = hash.Sum(digest[:0])
466 hash.Reset()
467
468 for i := 0; i < len(digest) && done < len(out); i++ {
469 out[done] ^= digest[i]
470 done++
471 }
472 incCounter(&counter)
473 }
474 }
475
476
477
478
479 var ErrMessageTooLong = errors.New("crypto/rsa: message too long for RSA key size")
480
481 func encrypt(pub *PublicKey, plaintext []byte) ([]byte, error) {
482 boring.Unreachable()
483
484 N, err := bigmod.NewModulusFromBig(pub.N)
485 if err != nil {
486 return nil, err
487 }
488 m, err := bigmod.NewNat().SetBytes(plaintext, N)
489 if err != nil {
490 return nil, err
491 }
492 e := uint(pub.E)
493
494 return bigmod.NewNat().ExpShortVarTime(m, e, N).Bytes(N), nil
495 }
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515 func EncryptOAEP(hash hash.Hash, random io.Reader, pub *PublicKey, msg []byte, label []byte) ([]byte, error) {
516
517
518
519
520
521
522 if err := checkPub(pub); err != nil {
523 return nil, err
524 }
525 hash.Reset()
526 k := pub.Size()
527 if len(msg) > k-2*hash.Size()-2 {
528 return nil, ErrMessageTooLong
529 }
530
531 if boring.Enabled && random == boring.RandReader {
532 bkey, err := boringPublicKey(pub)
533 if err != nil {
534 return nil, err
535 }
536 return boring.EncryptRSAOAEP(hash, hash, bkey, msg, label)
537 }
538 boring.UnreachableExceptTests()
539
540 hash.Write(label)
541 lHash := hash.Sum(nil)
542 hash.Reset()
543
544 em := make([]byte, k)
545 seed := em[1 : 1+hash.Size()]
546 db := em[1+hash.Size():]
547
548 copy(db[0:hash.Size()], lHash)
549 db[len(db)-len(msg)-1] = 1
550 copy(db[len(db)-len(msg):], msg)
551
552 _, err := io.ReadFull(random, seed)
553 if err != nil {
554 return nil, err
555 }
556
557 mgf1XOR(db, hash, seed)
558 mgf1XOR(seed, hash, db)
559
560 if boring.Enabled {
561 var bkey *boring.PublicKeyRSA
562 bkey, err = boringPublicKey(pub)
563 if err != nil {
564 return nil, err
565 }
566 return boring.EncryptRSANoPadding(bkey, em)
567 }
568
569 return encrypt(pub, em)
570 }
571
572
573
574 var ErrDecryption = errors.New("crypto/rsa: decryption error")
575
576
577
578 var ErrVerification = errors.New("crypto/rsa: verification error")
579
580
581
582 func (priv *PrivateKey) Precompute() {
583 if priv.Precomputed.n == nil && len(priv.Primes) == 2 {
584
585
586 var err error
587 priv.Precomputed.n, err = bigmod.NewModulusFromBig(priv.N)
588 if err != nil {
589 return
590 }
591 priv.Precomputed.p, err = bigmod.NewModulusFromBig(priv.Primes[0])
592 if err != nil {
593
594 priv.Precomputed.n = nil
595 return
596 }
597 priv.Precomputed.q, err = bigmod.NewModulusFromBig(priv.Primes[1])
598 if err != nil {
599
600 priv.Precomputed.n, priv.Precomputed.p = nil, nil
601 return
602 }
603 }
604
605
606 if priv.Precomputed.Dp != nil {
607 return
608 }
609
610 priv.Precomputed.Dp = new(big.Int).Sub(priv.Primes[0], bigOne)
611 priv.Precomputed.Dp.Mod(priv.D, priv.Precomputed.Dp)
612
613 priv.Precomputed.Dq = new(big.Int).Sub(priv.Primes[1], bigOne)
614 priv.Precomputed.Dq.Mod(priv.D, priv.Precomputed.Dq)
615
616 priv.Precomputed.Qinv = new(big.Int).ModInverse(priv.Primes[1], priv.Primes[0])
617
618 r := new(big.Int).Mul(priv.Primes[0], priv.Primes[1])
619 priv.Precomputed.CRTValues = make([]CRTValue, len(priv.Primes)-2)
620 for i := 2; i < len(priv.Primes); i++ {
621 prime := priv.Primes[i]
622 values := &priv.Precomputed.CRTValues[i-2]
623
624 values.Exp = new(big.Int).Sub(prime, bigOne)
625 values.Exp.Mod(priv.D, values.Exp)
626
627 values.R = new(big.Int).Set(r)
628 values.Coeff = new(big.Int).ModInverse(r, prime)
629
630 r.Mul(r, prime)
631 }
632 }
633
634 const withCheck = true
635 const noCheck = false
636
637
638
639
640 func decrypt(priv *PrivateKey, ciphertext []byte, check bool) ([]byte, error) {
641 if len(priv.Primes) <= 2 {
642 boring.Unreachable()
643 }
644
645 var (
646 err error
647 m, c *bigmod.Nat
648 N *bigmod.Modulus
649 t0 = bigmod.NewNat()
650 )
651 if priv.Precomputed.n == nil {
652 N, err = bigmod.NewModulusFromBig(priv.N)
653 if err != nil {
654 return nil, ErrDecryption
655 }
656 c, err = bigmod.NewNat().SetBytes(ciphertext, N)
657 if err != nil {
658 return nil, ErrDecryption
659 }
660 m = bigmod.NewNat().Exp(c, priv.D.Bytes(), N)
661 } else {
662 N = priv.Precomputed.n
663 P, Q := priv.Precomputed.p, priv.Precomputed.q
664 Qinv, err := bigmod.NewNat().SetBytes(priv.Precomputed.Qinv.Bytes(), P)
665 if err != nil {
666 return nil, ErrDecryption
667 }
668 c, err = bigmod.NewNat().SetBytes(ciphertext, N)
669 if err != nil {
670 return nil, ErrDecryption
671 }
672
673
674 m = bigmod.NewNat().Exp(t0.Mod(c, P), priv.Precomputed.Dp.Bytes(), P)
675
676 m2 := bigmod.NewNat().Exp(t0.Mod(c, Q), priv.Precomputed.Dq.Bytes(), Q)
677
678 m.Sub(t0.Mod(m2, P), P)
679
680 m.Mul(Qinv, P)
681
682 m.ExpandFor(N).Mul(t0.Mod(Q.Nat(), N), N)
683
684 m.Add(m2.ExpandFor(N), N)
685 }
686
687 if check {
688 c1 := bigmod.NewNat().ExpShortVarTime(m, uint(priv.E), N)
689 if c1.Equal(c) != 1 {
690 return nil, ErrDecryption
691 }
692 }
693
694 return m.Bytes(N), nil
695 }
696
697
698
699
700
701
702
703
704
705
706
707 func DecryptOAEP(hash hash.Hash, random io.Reader, priv *PrivateKey, ciphertext []byte, label []byte) ([]byte, error) {
708 return decryptOAEP(hash, hash, random, priv, ciphertext, label)
709 }
710
711 func decryptOAEP(hash, mgfHash hash.Hash, random io.Reader, priv *PrivateKey, ciphertext []byte, label []byte) ([]byte, error) {
712 if err := checkPub(&priv.PublicKey); err != nil {
713 return nil, err
714 }
715 k := priv.Size()
716 if len(ciphertext) > k ||
717 k < hash.Size()*2+2 {
718 return nil, ErrDecryption
719 }
720
721 if boring.Enabled {
722 bkey, err := boringPrivateKey(priv)
723 if err != nil {
724 return nil, err
725 }
726 out, err := boring.DecryptRSAOAEP(hash, mgfHash, bkey, ciphertext, label)
727 if err != nil {
728 return nil, ErrDecryption
729 }
730 return out, nil
731 }
732
733 em, err := decrypt(priv, ciphertext, noCheck)
734 if err != nil {
735 return nil, err
736 }
737
738 hash.Write(label)
739 lHash := hash.Sum(nil)
740 hash.Reset()
741
742 firstByteIsZero := subtle.ConstantTimeByteEq(em[0], 0)
743
744 seed := em[1 : hash.Size()+1]
745 db := em[hash.Size()+1:]
746
747 mgf1XOR(seed, mgfHash, db)
748 mgf1XOR(db, mgfHash, seed)
749
750 lHash2 := db[0:hash.Size()]
751
752
753
754
755
756 lHash2Good := subtle.ConstantTimeCompare(lHash, lHash2)
757
758
759
760
761
762
763 var lookingForIndex, index, invalid int
764 lookingForIndex = 1
765 rest := db[hash.Size():]
766
767 for i := 0; i < len(rest); i++ {
768 equals0 := subtle.ConstantTimeByteEq(rest[i], 0)
769 equals1 := subtle.ConstantTimeByteEq(rest[i], 1)
770 index = subtle.ConstantTimeSelect(lookingForIndex&equals1, i, index)
771 lookingForIndex = subtle.ConstantTimeSelect(equals1, 0, lookingForIndex)
772 invalid = subtle.ConstantTimeSelect(lookingForIndex&^equals0, 1, invalid)
773 }
774
775 if firstByteIsZero&lHash2Good&^invalid&^lookingForIndex != 1 {
776 return nil, ErrDecryption
777 }
778
779 return rest[index+1:], nil
780 }
781
View as plain text