Source file src/pkg/crypto/rsa/rsa.go
1
2
3
4
5
6 package rsa
7
8
9
10 import (
11 "crypto/rand"
12 "crypto/subtle"
13 "errors"
14 "hash"
15 "io"
16 "math/big"
17 )
18
19 var bigZero = big.NewInt(0)
20 var bigOne = big.NewInt(1)
21
22
23 type PublicKey struct {
24 N *big.Int
25 E int
26 }
27
28 var (
29 errPublicModulus = errors.New("crypto/rsa: missing public modulus")
30 errPublicExponentSmall = errors.New("crypto/rsa: public exponent too small")
31 errPublicExponentLarge = errors.New("crypto/rsa: public exponent too large")
32 )
33
34
35
36
37
38
39 func checkPub(pub *PublicKey) error {
40 if pub.N == nil {
41 return errPublicModulus
42 }
43 if pub.E < 2 {
44 return errPublicExponentSmall
45 }
46 if pub.E > 1<<31-1 {
47 return errPublicExponentLarge
48 }
49 return nil
50 }
51
52
53 type PrivateKey struct {
54 PublicKey
55 D *big.Int
56 Primes []*big.Int
57
58
59
60 Precomputed PrecomputedValues
61 }
62
63 type PrecomputedValues struct {
64 Dp, Dq *big.Int
65 Qinv *big.Int
66
67
68
69
70
71 CRTValues []CRTValue
72 }
73
74
75 type CRTValue struct {
76 Exp *big.Int
77 Coeff *big.Int
78 R *big.Int
79 }
80
81
82
83 func (priv *PrivateKey) Validate() error {
84 if err := checkPub(&priv.PublicKey); err != nil {
85 return err
86 }
87
88
89
90
91
92 for _, prime := range priv.Primes {
93 if !prime.ProbablyPrime(20) {
94 return errors.New("crypto/rsa: prime factor is composite")
95 }
96 }
97
98
99 modulus := new(big.Int).Set(bigOne)
100 for _, prime := range priv.Primes {
101 modulus.Mul(modulus, prime)
102 }
103 if modulus.Cmp(priv.N) != 0 {
104 return errors.New("crypto/rsa: invalid modulus")
105 }
106
107
108
109
110
111
112 congruence := new(big.Int)
113 de := new(big.Int).SetInt64(int64(priv.E))
114 de.Mul(de, priv.D)
115 for _, prime := range priv.Primes {
116 pminus1 := new(big.Int).Sub(prime, bigOne)
117 congruence.Mod(de, pminus1)
118 if congruence.Cmp(bigOne) != 0 {
119 return errors.New("crypto/rsa: invalid exponents")
120 }
121 }
122 return nil
123 }
124
125
126 func GenerateKey(random io.Reader, bits int) (priv *PrivateKey, err error) {
127 return GenerateMultiPrimeKey(random, 2, bits)
128 }
129
130
131
132
133
134
135
136
137
138
139
140 func GenerateMultiPrimeKey(random io.Reader, nprimes int, bits int) (priv *PrivateKey, err error) {
141 priv = new(PrivateKey)
142 priv.E = 65537
143
144 if nprimes < 2 {
145 return nil, errors.New("crypto/rsa: GenerateMultiPrimeKey: nprimes must be >= 2")
146 }
147
148 primes := make([]*big.Int, nprimes)
149
150 NextSetOfPrimes:
151 for {
152 todo := bits
153
154
155
156
157
158
159
160
161
162
163
164 if nprimes >= 7 {
165 todo += (nprimes - 2) / 5
166 }
167 for i := 0; i < nprimes; i++ {
168 primes[i], err = rand.Prime(random, todo/(nprimes-i))
169 if err != nil {
170 return nil, err
171 }
172 todo -= primes[i].BitLen()
173 }
174
175
176 for i, prime := range primes {
177 for j := 0; j < i; j++ {
178 if prime.Cmp(primes[j]) == 0 {
179 continue NextSetOfPrimes
180 }
181 }
182 }
183
184 n := new(big.Int).Set(bigOne)
185 totient := new(big.Int).Set(bigOne)
186 pminus1 := new(big.Int)
187 for _, prime := range primes {
188 n.Mul(n, prime)
189 pminus1.Sub(prime, bigOne)
190 totient.Mul(totient, pminus1)
191 }
192 if n.BitLen() != bits {
193
194
195
196 continue NextSetOfPrimes
197 }
198
199 g := new(big.Int)
200 priv.D = new(big.Int)
201 y := new(big.Int)
202 e := big.NewInt(int64(priv.E))
203 g.GCD(priv.D, y, e, totient)
204
205 if g.Cmp(bigOne) == 0 {
206 if priv.D.Sign() < 0 {
207 priv.D.Add(priv.D, totient)
208 }
209 priv.Primes = primes
210 priv.N = n
211
212 break
213 }
214 }
215
216 priv.Precompute()
217 return
218 }
219
220
221 func incCounter(c *[4]byte) {
222 if c[3]++; c[3] != 0 {
223 return
224 }
225 if c[2]++; c[2] != 0 {
226 return
227 }
228 if c[1]++; c[1] != 0 {
229 return
230 }
231 c[0]++
232 }
233
234
235
236 func mgf1XOR(out []byte, hash hash.Hash, seed []byte) {
237 var counter [4]byte
238 var digest []byte
239
240 done := 0
241 for done < len(out) {
242 hash.Write(seed)
243 hash.Write(counter[0:4])
244 digest = hash.Sum(digest[:0])
245 hash.Reset()
246
247 for i := 0; i < len(digest) && done < len(out); i++ {
248 out[done] ^= digest[i]
249 done++
250 }
251 incCounter(&counter)
252 }
253 }
254
255
256
257 var ErrMessageTooLong = errors.New("crypto/rsa: message too long for RSA public key size")
258
259 func encrypt(c *big.Int, pub *PublicKey, m *big.Int) *big.Int {
260 e := big.NewInt(int64(pub.E))
261 c.Exp(m, e, pub.N)
262 return c
263 }
264
265
266
267
268 func EncryptOAEP(hash hash.Hash, random io.Reader, pub *PublicKey, msg []byte, label []byte) (out []byte, err error) {
269 if err := checkPub(pub); err != nil {
270 return nil, err
271 }
272 hash.Reset()
273 k := (pub.N.BitLen() + 7) / 8
274 if len(msg) > k-2*hash.Size()-2 {
275 err = ErrMessageTooLong
276 return
277 }
278
279 hash.Write(label)
280 lHash := hash.Sum(nil)
281 hash.Reset()
282
283 em := make([]byte, k)
284 seed := em[1 : 1+hash.Size()]
285 db := em[1+hash.Size():]
286
287 copy(db[0:hash.Size()], lHash)
288 db[len(db)-len(msg)-1] = 1
289 copy(db[len(db)-len(msg):], msg)
290
291 _, err = io.ReadFull(random, seed)
292 if err != nil {
293 return
294 }
295
296 mgf1XOR(db, hash, seed)
297 mgf1XOR(seed, hash, db)
298
299 m := new(big.Int)
300 m.SetBytes(em)
301 c := encrypt(new(big.Int), pub, m)
302 out = c.Bytes()
303
304 if len(out) < k {
305
306 t := make([]byte, k)
307 copy(t[k-len(out):], out)
308 out = t
309 }
310
311 return
312 }
313
314
315
316 var ErrDecryption = errors.New("crypto/rsa: decryption error")
317
318
319
320 var ErrVerification = errors.New("crypto/rsa: verification error")
321
322
323
324 func modInverse(a, n *big.Int) (ia *big.Int, ok bool) {
325 g := new(big.Int)
326 x := new(big.Int)
327 y := new(big.Int)
328 g.GCD(x, y, a, n)
329 if g.Cmp(bigOne) != 0 {
330
331
332
333
334 return
335 }
336
337 if x.Cmp(bigOne) < 0 {
338
339
340 x.Add(x, n)
341 }
342
343 return x, true
344 }
345
346
347
348 func (priv *PrivateKey) Precompute() {
349 if priv.Precomputed.Dp != nil {
350 return
351 }
352
353 priv.Precomputed.Dp = new(big.Int).Sub(priv.Primes[0], bigOne)
354 priv.Precomputed.Dp.Mod(priv.D, priv.Precomputed.Dp)
355
356 priv.Precomputed.Dq = new(big.Int).Sub(priv.Primes[1], bigOne)
357 priv.Precomputed.Dq.Mod(priv.D, priv.Precomputed.Dq)
358
359 priv.Precomputed.Qinv = new(big.Int).ModInverse(priv.Primes[1], priv.Primes[0])
360
361 r := new(big.Int).Mul(priv.Primes[0], priv.Primes[1])
362 priv.Precomputed.CRTValues = make([]CRTValue, len(priv.Primes)-2)
363 for i := 2; i < len(priv.Primes); i++ {
364 prime := priv.Primes[i]
365 values := &priv.Precomputed.CRTValues[i-2]
366
367 values.Exp = new(big.Int).Sub(prime, bigOne)
368 values.Exp.Mod(priv.D, values.Exp)
369
370 values.R = new(big.Int).Set(r)
371 values.Coeff = new(big.Int).ModInverse(r, prime)
372
373 r.Mul(r, prime)
374 }
375 }
376
377
378
379 func decrypt(random io.Reader, priv *PrivateKey, c *big.Int) (m *big.Int, err error) {
380
381 if c.Cmp(priv.N) > 0 {
382 err = ErrDecryption
383 return
384 }
385
386 var ir *big.Int
387 if random != nil {
388
389
390
391
392
393 var r *big.Int
394
395 for {
396 r, err = rand.Int(random, priv.N)
397 if err != nil {
398 return
399 }
400 if r.Cmp(bigZero) == 0 {
401 r = bigOne
402 }
403 var ok bool
404 ir, ok = modInverse(r, priv.N)
405 if ok {
406 break
407 }
408 }
409 bigE := big.NewInt(int64(priv.E))
410 rpowe := new(big.Int).Exp(r, bigE, priv.N)
411 cCopy := new(big.Int).Set(c)
412 cCopy.Mul(cCopy, rpowe)
413 cCopy.Mod(cCopy, priv.N)
414 c = cCopy
415 }
416
417 if priv.Precomputed.Dp == nil {
418 m = new(big.Int).Exp(c, priv.D, priv.N)
419 } else {
420
421 m = new(big.Int).Exp(c, priv.Precomputed.Dp, priv.Primes[0])
422 m2 := new(big.Int).Exp(c, priv.Precomputed.Dq, priv.Primes[1])
423 m.Sub(m, m2)
424 if m.Sign() < 0 {
425 m.Add(m, priv.Primes[0])
426 }
427 m.Mul(m, priv.Precomputed.Qinv)
428 m.Mod(m, priv.Primes[0])
429 m.Mul(m, priv.Primes[1])
430 m.Add(m, m2)
431
432 for i, values := range priv.Precomputed.CRTValues {
433 prime := priv.Primes[2+i]
434 m2.Exp(c, values.Exp, prime)
435 m2.Sub(m2, m)
436 m2.Mul(m2, values.Coeff)
437 m2.Mod(m2, prime)
438 if m2.Sign() < 0 {
439 m2.Add(m2, prime)
440 }
441 m2.Mul(m2, values.R)
442 m.Add(m, m2)
443 }
444 }
445
446 if ir != nil {
447
448 m.Mul(m, ir)
449 m.Mod(m, priv.N)
450 }
451
452 return
453 }
454
455
456
457 func DecryptOAEP(hash hash.Hash, random io.Reader, priv *PrivateKey, ciphertext []byte, label []byte) (msg []byte, err error) {
458 if err := checkPub(&priv.PublicKey); err != nil {
459 return nil, err
460 }
461 k := (priv.N.BitLen() + 7) / 8
462 if len(ciphertext) > k ||
463 k < hash.Size()*2+2 {
464 err = ErrDecryption
465 return
466 }
467
468 c := new(big.Int).SetBytes(ciphertext)
469
470 m, err := decrypt(random, priv, c)
471 if err != nil {
472 return
473 }
474
475 hash.Write(label)
476 lHash := hash.Sum(nil)
477 hash.Reset()
478
479
480
481
482
483
484 em := leftPad(m.Bytes(), k)
485
486 firstByteIsZero := subtle.ConstantTimeByteEq(em[0], 0)
487
488 seed := em[1 : hash.Size()+1]
489 db := em[hash.Size()+1:]
490
491 mgf1XOR(seed, hash, db)
492 mgf1XOR(db, hash, seed)
493
494 lHash2 := db[0:hash.Size()]
495
496
497
498
499
500 lHash2Good := subtle.ConstantTimeCompare(lHash, lHash2)
501
502
503
504
505
506
507 var lookingForIndex, index, invalid int
508 lookingForIndex = 1
509 rest := db[hash.Size():]
510
511 for i := 0; i < len(rest); i++ {
512 equals0 := subtle.ConstantTimeByteEq(rest[i], 0)
513 equals1 := subtle.ConstantTimeByteEq(rest[i], 1)
514 index = subtle.ConstantTimeSelect(lookingForIndex&equals1, i, index)
515 lookingForIndex = subtle.ConstantTimeSelect(equals1, 0, lookingForIndex)
516 invalid = subtle.ConstantTimeSelect(lookingForIndex&^equals0, 1, invalid)
517 }
518
519 if firstByteIsZero&lHash2Good&^invalid&^lookingForIndex != 1 {
520 err = ErrDecryption
521 return
522 }
523
524 msg = rest[index+1:]
525 return
526 }
527
528
529
530 func leftPad(input []byte, size int) (out []byte) {
531 n := len(input)
532 if n > size {
533 n = size
534 }
535 out = make([]byte, size)
536 copy(out[len(out)-n:], input)
537 return
538 }
View as plain text