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