def generate_key(k, seed=None):
def modinv(a, m):<EOL><INDENT>"""<STR_LIT>"""<EOL>b = <NUM_LIT:1><EOL>while not (a * b) % m == <NUM_LIT:1>:<EOL><INDENT>b += <NUM_LIT:1><EOL><DEDENT>return b<EOL><DEDENT>def gen_prime(k, seed=None):<EOL><INDENT>"""<STR_LIT>"""<EOL>def is_prime(num):<EOL><INDENT>if num == <NUM_LIT:2>:<EOL><INDENT>return True<EOL><DEDENT>for i in range(<NUM_LIT:2>, int(num ** <NUM_LIT:0.5>) + <NUM_LIT:1>):<EOL><INDENT>if num % i == <NUM_LIT:0>:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL><DEDENT>random.seed(seed)<EOL>while True:<EOL><INDENT>key = random.randrange(int(<NUM_LIT:2> ** (k - <NUM_LIT:1>)), int(<NUM_LIT:2> ** k))<EOL>if is_prime(key):<EOL><INDENT>return key<EOL><DEDENT><DEDENT><DEDENT>p_size = k / <NUM_LIT:2><EOL>q_size = k - p_size<EOL>e = gen_prime(k, seed)  <EOL>while True:<EOL><INDENT>p = gen_prime(p_size, seed)<EOL>if p % e != <NUM_LIT:1>:<EOL><INDENT>break<EOL><DEDENT><DEDENT>while True:<EOL><INDENT>q = gen_prime(q_size, seed)<EOL>if q % e != <NUM_LIT:1>:<EOL><INDENT>break<EOL><DEDENT><DEDENT>n = p * q<EOL>l = (p - <NUM_LIT:1>) * (q - <NUM_LIT:1>)  <EOL>d = modinv(e, l)<EOL>return int(n), int(e), int(d)<EOL>
the RSA key generating algorithm
k is the number of bits in n