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