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