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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42 package rsa
43
44 import (
45 "crypto"
46 "crypto/internal/boring"
47 "crypto/internal/boring/bbig"
48 "crypto/internal/fips140/bigmod"
49 "crypto/internal/fips140/rsa"
50 "crypto/internal/fips140only"
51 "crypto/internal/rand"
52 cryptorand "crypto/rand"
53 "crypto/subtle"
54 "errors"
55 "fmt"
56 "internal/godebug"
57 "io"
58 "math"
59 "math/big"
60 )
61
62 var bigOne = big.NewInt(1)
63
64
65
66
67
68 type PublicKey struct {
69 N *big.Int
70 E int
71 }
72
73
74
75
76
77
78 func (pub *PublicKey) Size() int {
79 return (pub.N.BitLen() + 7) / 8
80 }
81
82
83 func (pub *PublicKey) Equal(x crypto.PublicKey) bool {
84 xx, ok := x.(*PublicKey)
85 if !ok {
86 return false
87 }
88 return bigIntEqual(pub.N, xx.N) && pub.E == xx.E
89 }
90
91
92
93 type OAEPOptions struct {
94
95 Hash crypto.Hash
96
97
98
99 MGFHash crypto.Hash
100
101
102
103 Label []byte
104 }
105
106
107
108
109
110 type PrivateKey struct {
111 PublicKey
112 D *big.Int
113 Primes []*big.Int
114
115
116
117
118 Precomputed PrecomputedValues
119 }
120
121
122 func (priv *PrivateKey) Public() crypto.PublicKey {
123 return &priv.PublicKey
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 if !priv.PublicKey.Equal(&xx.PublicKey) || !bigIntEqual(priv.D, xx.D) {
134 return false
135 }
136 if len(priv.Primes) != len(xx.Primes) {
137 return false
138 }
139 for i := range priv.Primes {
140 if !bigIntEqual(priv.Primes[i], xx.Primes[i]) {
141 return false
142 }
143 }
144 return true
145 }
146
147
148
149 func bigIntEqual(a, b *big.Int) bool {
150 return subtle.ConstantTimeCompare(a.Bytes(), b.Bytes()) == 1
151 }
152
153
154
155
156
157
158
159
160
161 func (priv *PrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
162 if pssOpts, ok := opts.(*PSSOptions); ok {
163 return SignPSS(rand, priv, pssOpts.Hash, digest, pssOpts)
164 }
165
166 return SignPKCS1v15(rand, priv, opts.HashFunc(), digest)
167 }
168
169
170
171
172 func (priv *PrivateKey) Decrypt(rand io.Reader, ciphertext []byte, opts crypto.DecrypterOpts) (plaintext []byte, err error) {
173 if opts == nil {
174 return DecryptPKCS1v15(rand, priv, ciphertext)
175 }
176
177 switch opts := opts.(type) {
178 case *OAEPOptions:
179 if opts.MGFHash == 0 {
180 return decryptOAEP(opts.Hash.New(), opts.Hash.New(), priv, ciphertext, opts.Label)
181 } else {
182 return decryptOAEP(opts.Hash.New(), opts.MGFHash.New(), priv, ciphertext, opts.Label)
183 }
184
185 case *PKCS1v15DecryptOptions:
186 if l := opts.SessionKeyLen; l > 0 {
187 plaintext = make([]byte, l)
188 if _, err := io.ReadFull(rand, plaintext); err != nil {
189 return nil, err
190 }
191 if err := DecryptPKCS1v15SessionKey(rand, priv, ciphertext, plaintext); err != nil {
192 return nil, err
193 }
194 return plaintext, nil
195 } else {
196 return DecryptPKCS1v15(rand, priv, ciphertext)
197 }
198
199 default:
200 return nil, errors.New("crypto/rsa: invalid options for Decrypt")
201 }
202 }
203
204 type PrecomputedValues struct {
205 Dp, Dq *big.Int
206 Qinv *big.Int
207
208
209
210
211
212
213
214
215
216
217 CRTValues []CRTValue
218
219 fips *rsa.PrivateKey
220 }
221
222
223 type CRTValue struct {
224 Exp *big.Int
225 Coeff *big.Int
226 R *big.Int
227 }
228
229
230
231
232
233 func (priv *PrivateKey) Validate() error {
234
235
236
237 if len(priv.Primes) < 2 {
238 return errors.New("crypto/rsa: missing primes")
239 }
240
241
242 if priv.precomputedIsConsistent() {
243 return nil
244 }
245 if priv.Precomputed.fips != nil {
246 return errors.New("crypto/rsa: precomputed values are inconsistent with the key")
247 }
248 _, err := priv.precompute()
249 return err
250 }
251
252 func (priv *PrivateKey) precomputedIsConsistent() bool {
253 if priv.Precomputed.fips == nil {
254 return false
255 }
256 N, e, d, P, Q, dP, dQ, qInv := priv.Precomputed.fips.Export()
257 if !bigIntEqualToBytes(priv.N, N) || priv.E != e || !bigIntEqualToBytes(priv.D, d) {
258 return false
259 }
260 if len(priv.Primes) != 2 {
261 return P == nil && Q == nil && dP == nil && dQ == nil && qInv == nil
262 }
263 return bigIntEqualToBytes(priv.Primes[0], P) &&
264 bigIntEqualToBytes(priv.Primes[1], Q) &&
265 bigIntEqualToBytes(priv.Precomputed.Dp, dP) &&
266 bigIntEqualToBytes(priv.Precomputed.Dq, dQ) &&
267 bigIntEqualToBytes(priv.Precomputed.Qinv, qInv)
268 }
269
270
271
272 func bigIntEqualToBytes(a *big.Int, b []byte) bool {
273 if a == nil || a.BitLen() > len(b)*8 {
274 return false
275 }
276 buf := a.FillBytes(make([]byte, len(b)))
277 return subtle.ConstantTimeCompare(buf, b) == 1
278 }
279
280
281
282 var rsa1024min = godebug.New("rsa1024min")
283
284 func checkKeySize(size int) error {
285 if size >= 1024 {
286 return nil
287 }
288 if rsa1024min.Value() == "0" {
289 rsa1024min.IncNonDefault()
290 return nil
291 }
292 return fmt.Errorf("crypto/rsa: %d-bit keys are insecure (see https://go.dev/pkg/crypto/rsa#hdr-Minimum_key_size)", size)
293 }
294
295 func checkPublicKeySize(k *PublicKey) error {
296 if k.N == nil {
297 return errors.New("crypto/rsa: missing public modulus")
298 }
299 return checkKeySize(k.N.BitLen())
300 }
301
302
303
304
305
306
307
308
309
310
311
312 func GenerateKey(random io.Reader, bits int) (*PrivateKey, error) {
313 if err := checkKeySize(bits); err != nil {
314 return nil, err
315 }
316
317 if boring.Enabled && rand.IsDefaultReader(random) &&
318 (bits == 2048 || bits == 3072 || bits == 4096) {
319 bN, bE, bD, bP, bQ, bDp, bDq, bQinv, err := boring.GenerateKeyRSA(bits)
320 if err != nil {
321 return nil, err
322 }
323 N := bbig.Dec(bN)
324 E := bbig.Dec(bE)
325 D := bbig.Dec(bD)
326 P := bbig.Dec(bP)
327 Q := bbig.Dec(bQ)
328 Dp := bbig.Dec(bDp)
329 Dq := bbig.Dec(bDq)
330 Qinv := bbig.Dec(bQinv)
331 e64 := E.Int64()
332 if !E.IsInt64() || int64(int(e64)) != e64 {
333 return nil, errors.New("crypto/rsa: generated key exponent too large")
334 }
335
336 key := &PrivateKey{
337 PublicKey: PublicKey{
338 N: N,
339 E: int(e64),
340 },
341 D: D,
342 Primes: []*big.Int{P, Q},
343 Precomputed: PrecomputedValues{
344 Dp: Dp,
345 Dq: Dq,
346 Qinv: Qinv,
347 CRTValues: make([]CRTValue, 0),
348 },
349 }
350 return key, nil
351 }
352
353 random = rand.CustomReader(random)
354
355 if fips140only.Enforced() && bits < 2048 {
356 return nil, errors.New("crypto/rsa: use of keys smaller than 2048 bits is not allowed in FIPS 140-only mode")
357 }
358 if fips140only.Enforced() && bits%2 == 1 {
359 return nil, errors.New("crypto/rsa: use of keys with odd size is not allowed in FIPS 140-only mode")
360 }
361 if fips140only.Enforced() && !fips140only.ApprovedRandomReader(random) {
362 return nil, errors.New("crypto/rsa: only crypto/rand.Reader is allowed in FIPS 140-only mode")
363 }
364
365 k, err := rsa.GenerateKey(random, bits)
366 if bits < 256 && err != nil {
367
368
369
370
371
372
373
374
375
376
377 for i := 1; i < 8 && err != nil; i++ {
378 k, err = rsa.GenerateKey(random, bits)
379 }
380 }
381 if err != nil {
382 return nil, err
383 }
384 N, e, d, p, q, dP, dQ, qInv := k.Export()
385 key := &PrivateKey{
386 PublicKey: PublicKey{
387 N: new(big.Int).SetBytes(N),
388 E: e,
389 },
390 D: new(big.Int).SetBytes(d),
391 Primes: []*big.Int{
392 new(big.Int).SetBytes(p),
393 new(big.Int).SetBytes(q),
394 },
395 Precomputed: PrecomputedValues{
396 fips: k,
397 Dp: new(big.Int).SetBytes(dP),
398 Dq: new(big.Int).SetBytes(dQ),
399 Qinv: new(big.Int).SetBytes(qInv),
400 CRTValues: make([]CRTValue, 0),
401 },
402 }
403 return key, nil
404 }
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429 func GenerateMultiPrimeKey(random io.Reader, nprimes int, bits int) (*PrivateKey, error) {
430 if nprimes == 2 {
431 return GenerateKey(random, bits)
432 }
433 if fips140only.Enforced() {
434 return nil, errors.New("crypto/rsa: multi-prime RSA is not allowed in FIPS 140-only mode")
435 }
436
437 random = rand.CustomReader(random)
438
439 priv := new(PrivateKey)
440 priv.E = 65537
441
442 if nprimes < 2 {
443 return nil, errors.New("crypto/rsa: GenerateMultiPrimeKey: nprimes must be >= 2")
444 }
445
446 if bits < 64 {
447 primeLimit := float64(uint64(1) << uint(bits/nprimes))
448
449 pi := primeLimit / (math.Log(primeLimit) - 1)
450
451
452 pi /= 4
453
454
455 pi /= 2
456 if pi <= float64(nprimes) {
457 return nil, errors.New("crypto/rsa: too few primes of given length to generate an RSA key")
458 }
459 }
460
461 primes := make([]*big.Int, nprimes)
462
463 NextSetOfPrimes:
464 for {
465 todo := bits
466
467
468
469
470
471
472
473
474
475
476
477 if nprimes >= 7 {
478 todo += (nprimes - 2) / 5
479 }
480 for i := 0; i < nprimes; i++ {
481 var err error
482 primes[i], err = cryptorand.Prime(random, todo/(nprimes-i))
483 if err != nil {
484 return nil, err
485 }
486 todo -= primes[i].BitLen()
487 }
488
489
490 for i, prime := range primes {
491 for j := 0; j < i; j++ {
492 if prime.Cmp(primes[j]) == 0 {
493 continue NextSetOfPrimes
494 }
495 }
496 }
497
498 n := new(big.Int).Set(bigOne)
499 totient := new(big.Int).Set(bigOne)
500 pminus1 := new(big.Int)
501 for _, prime := range primes {
502 n.Mul(n, prime)
503 pminus1.Sub(prime, bigOne)
504 totient.Mul(totient, pminus1)
505 }
506 if n.BitLen() != bits {
507
508
509
510 continue NextSetOfPrimes
511 }
512
513 priv.D = new(big.Int)
514 e := big.NewInt(int64(priv.E))
515 ok := priv.D.ModInverse(e, totient)
516
517 if ok != nil {
518 priv.Primes = primes
519 priv.N = n
520 break
521 }
522 }
523
524 priv.Precompute()
525 if err := priv.Validate(); err != nil {
526 return nil, err
527 }
528
529 return priv, nil
530 }
531
532
533
534
535 var ErrMessageTooLong = errors.New("crypto/rsa: message too long for RSA key size")
536
537
538
539 var ErrDecryption = errors.New("crypto/rsa: decryption error")
540
541
542
543 var ErrVerification = errors.New("crypto/rsa: verification error")
544
545
546
547
548
549
550
551
552
553
554
555
556
557 func (priv *PrivateKey) Precompute() {
558 if priv.precomputedIsConsistent() {
559 return
560 }
561
562 precomputed, err := priv.precompute()
563 if err != nil {
564
565
566 priv.Precomputed.fips = nil
567 return
568 }
569 priv.Precomputed = precomputed
570 }
571
572
573
574
575 func (priv *PrivateKey) precompute() (PrecomputedValues, error) {
576 var precomputed PrecomputedValues
577
578 if priv.N == nil {
579 return precomputed, errors.New("crypto/rsa: missing public modulus")
580 }
581 if priv.D == nil {
582 return precomputed, errors.New("crypto/rsa: missing private exponent")
583 }
584 if len(priv.Primes) != 2 {
585 return priv.precomputeLegacy()
586 }
587 if priv.Primes[0] == nil {
588 return precomputed, errors.New("crypto/rsa: prime P is nil")
589 }
590 if priv.Primes[1] == nil {
591 return precomputed, errors.New("crypto/rsa: prime Q is nil")
592 }
593
594
595 if priv.Precomputed.Dp != nil && priv.Precomputed.Dq != nil && priv.Precomputed.Qinv != nil {
596 k, err := rsa.NewPrivateKeyWithPrecomputation(priv.N.Bytes(), priv.E, priv.D.Bytes(),
597 priv.Primes[0].Bytes(), priv.Primes[1].Bytes(),
598 priv.Precomputed.Dp.Bytes(), priv.Precomputed.Dq.Bytes(), priv.Precomputed.Qinv.Bytes())
599 if err != nil {
600 return precomputed, err
601 }
602 precomputed = priv.Precomputed
603 precomputed.fips = k
604 precomputed.CRTValues = make([]CRTValue, 0)
605 return precomputed, nil
606 }
607
608 k, err := rsa.NewPrivateKey(priv.N.Bytes(), priv.E, priv.D.Bytes(),
609 priv.Primes[0].Bytes(), priv.Primes[1].Bytes())
610 if err != nil {
611 return precomputed, err
612 }
613
614 precomputed.fips = k
615 _, _, _, _, _, dP, dQ, qInv := k.Export()
616 precomputed.Dp = new(big.Int).SetBytes(dP)
617 precomputed.Dq = new(big.Int).SetBytes(dQ)
618 precomputed.Qinv = new(big.Int).SetBytes(qInv)
619 precomputed.CRTValues = make([]CRTValue, 0)
620 return precomputed, nil
621 }
622
623 func (priv *PrivateKey) precomputeLegacy() (PrecomputedValues, error) {
624 var precomputed PrecomputedValues
625
626 k, err := rsa.NewPrivateKeyWithoutCRT(priv.N.Bytes(), priv.E, priv.D.Bytes())
627 if err != nil {
628 return precomputed, err
629 }
630 precomputed.fips = k
631
632 if len(priv.Primes) < 2 {
633 return precomputed, nil
634 }
635
636
637 for _, prime := range priv.Primes {
638 if prime == nil {
639 return precomputed, errors.New("crypto/rsa: prime factor is nil")
640 }
641 if prime.Cmp(bigOne) <= 0 {
642 return precomputed, errors.New("crypto/rsa: prime factor is <= 1")
643 }
644 }
645
646 precomputed.Dp = new(big.Int).Sub(priv.Primes[0], bigOne)
647 precomputed.Dp.Mod(priv.D, precomputed.Dp)
648
649 precomputed.Dq = new(big.Int).Sub(priv.Primes[1], bigOne)
650 precomputed.Dq.Mod(priv.D, precomputed.Dq)
651
652 precomputed.Qinv = new(big.Int).ModInverse(priv.Primes[1], priv.Primes[0])
653 if precomputed.Qinv == nil {
654 return precomputed, errors.New("crypto/rsa: prime factors are not relatively prime")
655 }
656
657 r := new(big.Int).Mul(priv.Primes[0], priv.Primes[1])
658 precomputed.CRTValues = make([]CRTValue, len(priv.Primes)-2)
659 for i := 2; i < len(priv.Primes); i++ {
660 prime := priv.Primes[i]
661 values := &precomputed.CRTValues[i-2]
662
663 values.Exp = new(big.Int).Sub(prime, bigOne)
664 values.Exp.Mod(priv.D, values.Exp)
665
666 values.R = new(big.Int).Set(r)
667 values.Coeff = new(big.Int).ModInverse(r, prime)
668 if values.Coeff == nil {
669 return precomputed, errors.New("crypto/rsa: prime factors are not relatively prime")
670 }
671
672 r.Mul(r, prime)
673 }
674
675 return precomputed, nil
676 }
677
678 func fipsPublicKey(pub *PublicKey) (*rsa.PublicKey, error) {
679 N, err := bigmod.NewModulus(pub.N.Bytes())
680 if err != nil {
681 return nil, err
682 }
683 return &rsa.PublicKey{N: N, E: pub.E}, nil
684 }
685
686
687
688
689
690 func fipsPrivateKey(priv *PrivateKey) (*rsa.PrivateKey, error) {
691 if priv.Precomputed.fips != nil {
692 return priv.Precomputed.fips, nil
693 }
694 precomputed, err := priv.precompute()
695 if err != nil {
696 return nil, err
697 }
698 return precomputed.fips, nil
699 }
700
View as plain text