@@ 348-370 (lines=23) @@ | ||
345 | return (a, lx, ly) #Return only positive values |
|
346 | ||
347 | # Main function: calculate encryption and decryption keys |
|
348 | def calculate_keys(p, q, nbits): |
|
349 | """Calculates an encryption and a decryption key for p and q, and |
|
350 | returns them as a tuple (e, d)""" |
|
351 | ||
352 | n = p * q |
|
353 | phi_n = (p-1) * (q-1) |
|
354 | ||
355 | while True: |
|
356 | # Make sure e has enough bits so we ensure "wrapping" through |
|
357 | # modulo n |
|
358 | e = max(65537,getprime(nbits/4)) |
|
359 | if are_relatively_prime(e, n) and are_relatively_prime(e, phi_n): break |
|
360 | ||
361 | (d, i, j) = extended_gcd(e, phi_n) |
|
362 | ||
363 | if not d == 1: |
|
364 | raise Exception("e (%d) and phi_n (%d) are not relatively prime" % (e, phi_n)) |
|
365 | if (i < 0): |
|
366 | raise Exception("New extended_gcd shouldn't return negative values") |
|
367 | if not (e * i) % phi_n == 1: |
|
368 | raise Exception("e (%d) and i (%d) are not mult. inv. modulo phi_n (%d)" % (e, i, phi_n)) |
|
369 | ||
370 | return (e, i) |
|
371 | ||
372 | ||
373 | def gen_keys(nbits): |
@@ 275-296 (lines=22) @@ | ||
272 | return (d, l, k - l*r) |
|
273 | ||
274 | # Main function: calculate encryption and decryption keys |
|
275 | def calculate_keys(p, q, nbits): |
|
276 | """Calculates an encryption and a decryption key for p and q, and |
|
277 | returns them as a tuple (e, d)""" |
|
278 | ||
279 | n = p * q |
|
280 | phi_n = (p-1) * (q-1) |
|
281 | ||
282 | while True: |
|
283 | # Make sure e has enough bits so we ensure "wrapping" through |
|
284 | # modulo n |
|
285 | e = getprime(max(8, nbits/2)) |
|
286 | if are_relatively_prime(e, n) and are_relatively_prime(e, phi_n): break |
|
287 | ||
288 | (d, i, j) = extended_euclid_gcd(e, phi_n) |
|
289 | ||
290 | if not d == 1: |
|
291 | raise Exception("e (%d) and phi_n (%d) are not relatively prime" % (e, phi_n)) |
|
292 | ||
293 | if not (e * i) % phi_n == 1: |
|
294 | raise Exception("e (%d) and i (%d) are not mult. inv. modulo phi_n (%d)" % (e, i, phi_n)) |
|
295 | ||
296 | return (e, i) |
|
297 | ||
298 | ||
299 | def gen_keys(nbits): |