Python/ciphers/rsa_key_generator.py
CarsonHam 61f3119467
Change occurrences of str.format to f-strings (#4118)
* f-string update rsa_cipher.py

* f-string update rsa_key_generator.py

* f-string update burrows_wheeler.py

* f-string update non_recursive_segment_tree.py

* f-string update red_black_tree.py

* f-string update deque_doubly.py

* f-string update climbing_stairs.py

* f-string update iterating_through_submasks.py

* f-string update knn_sklearn.py

* f-string update 3n_plus_1.py

* f-string update quadratic_equations_complex_numbers.py

* f-string update nth_fibonacci_using_matrix_exponentiation.py

* f-string update sherman_morrison.py

* f-string update levenshtein_distance.py

* fix lines that were too long
2021-02-23 11:23:49 +05:30

61 lines
1.8 KiB
Python

import os
import random
import sys
from typing import Tuple
from . import cryptomath_module as cryptoMath
from . import rabin_miller as rabinMiller
def main():
print("Making key files...")
makeKeyFiles("rsa", 1024)
print("Key files generation successful.")
def generateKey(keySize: int) -> Tuple[Tuple[int, int], Tuple[int, int]]:
print("Generating prime p...")
p = rabinMiller.generateLargePrime(keySize)
print("Generating prime q...")
q = rabinMiller.generateLargePrime(keySize)
n = p * q
print("Generating e that is relatively prime to (p - 1) * (q - 1)...")
while True:
e = random.randrange(2 ** (keySize - 1), 2 ** (keySize))
if cryptoMath.gcd(e, (p - 1) * (q - 1)) == 1:
break
print("Calculating d that is mod inverse of e...")
d = cryptoMath.findModInverse(e, (p - 1) * (q - 1))
publicKey = (n, e)
privateKey = (n, d)
return (publicKey, privateKey)
def makeKeyFiles(name: int, keySize: int) -> None:
if os.path.exists("%s_pubkey.txt" % (name)) or os.path.exists(
"%s_privkey.txt" % (name)
):
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."
% (name, name)
)
sys.exit()
publicKey, privateKey = generateKey(keySize)
print("\nWriting public key to file %s_pubkey.txt..." % name)
with open("%s_pubkey.txt" % name, "w") as out_file:
out_file.write(f"{keySize},{publicKey[0]},{publicKey[1]}")
print("Writing private key to file %s_privkey.txt..." % name)
with open("%s_privkey.txt" % name, "w") as out_file:
out_file.write(f"{keySize},{privateKey[0]},{privateKey[1]}")
if __name__ == "__main__":
main()