Python/ciphers/rsa_key_generator.py

58 lines
1.7 KiB
Python
Raw Normal View History

import os
import random
import sys
from . import cryptomath_module as cryptoMath
from . import rabin_miller as rabinMiller
2016-09-06 12:23:48 +00:00
2019-10-05 05:14:13 +00:00
def main() -> None:
2019-10-05 05:14:13 +00:00
print("Making key files...")
makeKeyFiles("rsa", 1024)
print("Key files generation successful.")
2016-09-06 12:23:48 +00:00
def generateKey(keySize: int) -> tuple[tuple[int, int], tuple[int, int]]:
2019-10-05 05:14:13 +00:00
print("Generating prime p...")
2016-09-06 12:23:48 +00:00
p = rabinMiller.generateLargePrime(keySize)
2019-10-05 05:14:13 +00:00
print("Generating prime q...")
2016-09-06 12:23:48 +00:00
q = rabinMiller.generateLargePrime(keySize)
n = p * q
2019-10-05 05:14:13 +00:00
print("Generating e that is relatively prime to (p - 1) * (q - 1)...")
2016-09-06 12:23:48 +00:00
while True:
e = random.randrange(2 ** (keySize - 1), 2 ** (keySize))
if cryptoMath.gcd(e, (p - 1) * (q - 1)) == 1:
break
2019-10-05 05:14:13 +00:00
print("Calculating d that is mod inverse of e...")
d = cryptoMath.find_mod_inverse(e, (p - 1) * (q - 1))
2016-09-06 12:23:48 +00:00
publicKey = (n, e)
privateKey = (n, d)
return (publicKey, privateKey)
2019-10-05 05:14:13 +00:00
def makeKeyFiles(name: str, keySize: int) -> None:
if os.path.exists(f"{name}_pubkey.txt") or os.path.exists(f"{name}_privkey.txt"):
2019-10-05 05:14:13 +00:00
print("\nWARNING:")
print(
'"%s_pubkey.txt" or "%s_privkey.txt" already exists. \n'
"Use a different name or delete these files and re-run this program."
2019-10-05 05:14:13 +00:00
% (name, name)
)
2016-09-06 12:23:48 +00:00
sys.exit()
publicKey, privateKey = generateKey(keySize)
print(f"\nWriting public key to file {name}_pubkey.txt...")
with open(f"{name}_pubkey.txt", "w") as out_file:
out_file.write(f"{keySize},{publicKey[0]},{publicKey[1]}")
2019-10-05 05:14:13 +00:00
print(f"Writing private key to file {name}_privkey.txt...")
with open(f"{name}_privkey.txt", "w") as out_file:
out_file.write(f"{keySize},{privateKey[0]},{privateKey[1]}")
2016-09-06 12:23:48 +00:00
2019-10-05 05:14:13 +00:00
if __name__ == "__main__":
2016-09-06 12:23:48 +00:00
main()