1
2
3
4
5 package rsa
6
7 import (
8 "crypto/internal/fips140"
9 "crypto/internal/fips140/bigmod"
10 "crypto/internal/fips140/drbg"
11 "errors"
12 "io"
13 )
14
15
16
17 func GenerateKey(rand io.Reader, bits int) (*PrivateKey, error) {
18 if bits < 32 {
19 return nil, errors.New("rsa: key too small")
20 }
21 fips140.RecordApproved()
22 if bits < 2048 || bits%2 == 1 {
23 fips140.RecordNonApproved()
24 }
25
26 for {
27 p, err := randomPrime(rand, (bits+1)/2)
28 if err != nil {
29 return nil, err
30 }
31 q, err := randomPrime(rand, bits/2)
32 if err != nil {
33 return nil, err
34 }
35
36 P, err := bigmod.NewModulus(p)
37 if err != nil {
38 return nil, err
39 }
40 Q, err := bigmod.NewModulus(q)
41 if err != nil {
42 return nil, err
43 }
44
45 if Q.Nat().ExpandFor(P).Equal(P.Nat()) == 1 {
46 return nil, errors.New("rsa: generated p == q, random source is broken")
47 }
48
49 N, err := bigmod.NewModulusProduct(p, q)
50 if err != nil {
51 return nil, err
52 }
53 if N.BitLen() != bits {
54 return nil, errors.New("rsa: internal error: modulus size incorrect")
55 }
56
57
58
59
60
61
62
63
64
65
66
67
68
69 λ, err := totient(P, Q)
70 if err == errDivisorTooLarge {
71
72 continue
73 }
74 if err != nil {
75 return nil, err
76 }
77
78 e := bigmod.NewNat().SetUint(65537)
79 d, ok := bigmod.NewNat().InverseVarTime(e, λ)
80 if !ok {
81
82
83
84
85
86
87
88 continue
89 }
90
91 if e.ExpandFor(λ).Mul(d, λ).IsOne() == 0 {
92 return nil, errors.New("rsa: internal error: e*d != 1 mod λ(N)")
93 }
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108 k, err := newPrivateKey(N, 65537, d, P, Q)
109 if err != nil {
110 return nil, err
111 }
112
113 if k.fipsApproved {
114 fips140.PCT("RSA sign and verify PCT", func() error {
115 hash := []byte{
116 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
117 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
118 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
119 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
120 }
121 sig, err := signPKCS1v15(k, "SHA-256", hash)
122 if err != nil {
123 return err
124 }
125 return verifyPKCS1v15(k.PublicKey(), "SHA-256", hash, sig)
126 })
127 }
128
129 return k, nil
130 }
131 }
132
133
134 var errDivisorTooLarge = errors.New("divisor too large")
135
136
137 func totient(p, q *bigmod.Modulus) (*bigmod.Modulus, error) {
138 a, b := p.Nat().SubOne(p), q.Nat().SubOne(q)
139
140
141
142
143
144
145
146 az, bz := a.TrailingZeroBitsVarTime(), b.TrailingZeroBitsVarTime()
147 if az < bz {
148 a = a.ShiftRightVarTime(az)
149 } else {
150 b = b.ShiftRightVarTime(bz)
151 }
152
153 gcd, err := bigmod.NewNat().GCDVarTime(a, b)
154 if err != nil {
155 return nil, err
156 }
157 if gcd.IsOdd() == 0 {
158 return nil, errors.New("rsa: internal error: gcd(a, b) is even")
159 }
160
161
162
163
164
165
166 if gcd.BitLenVarTime() > 32 {
167 return nil, errDivisorTooLarge
168 }
169 if gcd.IsZero() == 1 || gcd.Bits()[0] == 0 {
170 return nil, errors.New("rsa: internal error: gcd(a, b) is zero")
171 }
172 if rem := b.DivShortVarTime(gcd.Bits()[0]); rem != 0 {
173 return nil, errors.New("rsa: internal error: b is not divisible by gcd(a, b)")
174 }
175
176 return bigmod.NewModulusProduct(a.Bytes(p), b.Bytes(q))
177 }
178
179
180
181 func randomPrime(rand io.Reader, bits int) ([]byte, error) {
182 if bits < 16 {
183 return nil, errors.New("rsa: prime size must be at least 16 bits")
184 }
185
186 b := make([]byte, (bits+7)/8)
187 for {
188 if err := drbg.ReadWithReader(rand, b); err != nil {
189 return nil, err
190 }
191 if excess := len(b)*8 - bits; excess != 0 {
192 b[0] >>= excess
193 }
194
195
196
197
198
199 if excess := len(b)*8 - bits; excess < 7 {
200 b[0] |= 0b1100_0000 >> excess
201 } else {
202 b[0] |= 0b0000_0001
203 b[1] |= 0b1000_0000
204 }
205
206
207 b[len(b)-1] |= 1
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225 if isPrime(b) {
226 return b, nil
227 }
228 }
229 }
230
231
232
233
234
235
236
237
238 func isPrime(w []byte) bool {
239 mr, err := millerRabinSetup(w)
240 if err != nil {
241
242 return false
243 }
244
245 primes, err := bigmod.NewNat().SetBytes(productOfPrimes, mr.w)
246
247
248 if err == nil {
249 _, hasInverse := primes.InverseVarTime(primes, mr.w)
250 if !hasInverse {
251
252
253 return false
254 }
255 }
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270 bits := mr.w.BitLen()
271 var iterations int
272 switch {
273 case bits >= 3747:
274 iterations = 3
275 case bits >= 1345:
276 iterations = 4
277 case bits >= 476:
278 iterations = 5
279 case bits >= 400:
280 iterations = 6
281 case bits >= 347:
282 iterations = 7
283 case bits >= 308:
284 iterations = 8
285 case bits >= 55:
286 iterations = 27
287 default:
288 iterations = 34
289 }
290
291 b := make([]byte, (bits+7)/8)
292 for {
293 drbg.Read(b)
294 if excess := len(b)*8 - bits; excess != 0 {
295 b[0] >>= excess
296 }
297 result, err := millerRabinIteration(mr, b)
298 if err != nil {
299
300 continue
301 }
302 if result == millerRabinCOMPOSITE {
303 return false
304 }
305 iterations--
306 if iterations == 0 {
307 return true
308 }
309 }
310 }
311
312
313
314
315
316
317
318
319 var productOfPrimes = []byte{
320 0x10, 0x6a, 0xa9, 0xfb, 0x76, 0x46, 0xfa, 0x6e, 0xb0, 0x81, 0x3c, 0x28, 0xc5, 0xd5, 0xf0, 0x9f,
321 0x07, 0x7e, 0xc3, 0xba, 0x23, 0x8b, 0xfb, 0x99, 0xc1, 0xb6, 0x31, 0xa2, 0x03, 0xe8, 0x11, 0x87,
322 0x23, 0x3d, 0xb1, 0x17, 0xcb, 0xc3, 0x84, 0x05, 0x6e, 0xf0, 0x46, 0x59, 0xa4, 0xa1, 0x1d, 0xe4,
323 0x9f, 0x7e, 0xcb, 0x29, 0xba, 0xda, 0x8f, 0x98, 0x0d, 0xec, 0xec, 0xe9, 0x2e, 0x30, 0xc4, 0x8f,
324 }
325
326 type millerRabin struct {
327 w *bigmod.Modulus
328 a uint
329 m []byte
330 }
331
332
333
334 func millerRabinSetup(w []byte) (*millerRabin, error) {
335 mr := &millerRabin{}
336
337
338 wm, err := bigmod.NewModulus(w)
339 if err != nil {
340 return nil, err
341 }
342 if wm.Nat().IsOdd() == 0 {
343 return nil, errors.New("candidate is even")
344 }
345 mr.w = wm
346
347
348 wMinus1 := mr.w.Nat().SubOne(mr.w)
349 if wMinus1.IsZero() == 1 {
350 return nil, errors.New("candidate is one")
351 }
352 mr.a = wMinus1.TrailingZeroBitsVarTime()
353
354
355
356 m := wMinus1.ShiftRightVarTime(mr.a)
357 mr.m = m.Bytes(mr.w)
358 for mr.m[0] == 0 {
359 mr.m = mr.m[1:]
360 }
361
362 return mr, nil
363 }
364
365 const millerRabinCOMPOSITE = false
366 const millerRabinPOSSIBLYPRIME = true
367
368 func millerRabinIteration(mr *millerRabin, bb []byte) (bool, error) {
369
370 if len(bb) != (mr.w.BitLen()+7)/8 {
371 return false, errors.New("incorrect length")
372 }
373 b := bigmod.NewNat()
374 if _, err := b.SetBytes(bb, mr.w); err != nil {
375 return false, err
376 }
377 if b.IsZero() == 1 || b.IsOne() == 1 || b.IsMinusOne(mr.w) == 1 {
378 return false, errors.New("out-of-range candidate")
379 }
380
381
382
383
384
385
386
387 z := bigmod.NewNat().Exp(b, mr.m, mr.w)
388 if z.IsOne() == 1 || z.IsMinusOne(mr.w) == 1 {
389 return millerRabinPOSSIBLYPRIME, nil
390 }
391
392
393 for range mr.a - 1 {
394 z.Mul(z, mr.w)
395 if z.IsMinusOne(mr.w) == 1 {
396 return millerRabinPOSSIBLYPRIME, nil
397 }
398 if z.IsOne() == 1 {
399
400 break
401 }
402 }
403
404 return millerRabinCOMPOSITE, nil
405 }
406
View as plain text