MCPcopy Create free account
hub / github.com/ActiveState/code / keygen

Function keygen

recipes/Python/578797_Public_Key_Encryption_RSA/recipe-578797.py:84–112  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

82
83
84def 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
115def encode(msg, pubkey, verbose=False):

Callers 1

mainFunction · 0.70

Calls 6

randrangeClass · 0.90
randprimeFunction · 0.70
multinvFunction · 0.70
gcdFunction · 0.50
powFunction · 0.50
KeyClass · 0.50

Tested by

no test coverage detected