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