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