Generate public and private keys from primes up to N. Optionally, specify the public key exponent (65537 is popular choice). >>> pubkey, privkey = keygen(2**64) >>> msg = 123456789012345 >>> coded = pow(msg, *pubkey) >>> plain = pow(coded, *privkey) >>>
(n, public=None)
| 82 | |
| 83 | |
| 84 | def keygen(n, public=None): |
| 85 | """ Generate public and private keys from primes up to N. |
| 86 | |
| 87 | Optionally, specify the public key exponent (65537 is popular choice). |
| 88 | |
| 89 | >>> pubkey, privkey = keygen(2**64) |
| 90 | >>> msg = 123456789012345 |
| 91 | >>> coded = pow(msg, *pubkey) |
| 92 | >>> plain = pow(coded, *privkey) |
| 93 | >>> assert msg == plain |
| 94 | |
| 95 | """ |
| 96 | # http://en.wikipedia.org/wiki/RSA |
| 97 | prime1 = randprime(n) |
| 98 | prime2 = randprime(n) |
| 99 | composite = prime1 * prime2 |
| 100 | totient = (prime1 - 1) * (prime2 - 1) |
| 101 | if public is None: |
| 102 | private = None |
| 103 | while True: |
| 104 | private = randrange(totient) |
| 105 | if gcd(private, totient) == 1: |
| 106 | break |
| 107 | public = multinv(totient, private) |
| 108 | else: |
| 109 | private = multinv(totient, public) |
| 110 | assert public * private % totient == gcd(public, totient) == gcd(private, totient) == 1 |
| 111 | assert pow(pow(1234567, public, composite), private, composite) == 1234567 |
| 112 | return KeyPair(Key(public, composite), Key(private, composite)) |
| 113 | |
| 114 | |
| 115 | def encode(msg, pubkey, verbose=False): |