2020-05-01 21:36:35 +00:00
|
|
|
import os
|
|
|
|
import random
|
|
|
|
import sys
|
|
|
|
|
2020-09-28 21:41:04 +00:00
|
|
|
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
|
|
|
|
2016-09-06 12:23:48 +00:00
|
|
|
def main():
|
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):
|
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...")
|
2016-09-06 12:23:48 +00:00
|
|
|
d = cryptoMath.findModInverse(e, (p - 1) * (q - 1))
|
|
|
|
|
|
|
|
publicKey = (n, e)
|
|
|
|
privateKey = (n, d)
|
|
|
|
return (publicKey, privateKey)
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2016-09-06 12:23:48 +00:00
|
|
|
def makeKeyFiles(name, keySize):
|
2019-10-05 05:14:13 +00:00
|
|
|
if os.path.exists("%s_pubkey.txt" % (name)) or os.path.exists(
|
|
|
|
"%s_privkey.txt" % (name)
|
|
|
|
):
|
|
|
|
print("\nWARNING:")
|
|
|
|
print(
|
2020-05-01 21:36:35 +00:00
|
|
|
'"%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)
|
2019-10-05 05:14:13 +00:00
|
|
|
print("\nWriting public key to file %s_pubkey.txt..." % name)
|
2020-01-18 12:24:33 +00:00
|
|
|
with open("%s_pubkey.txt" % name, "w") as out_file:
|
|
|
|
out_file.write("{},{},{}".format(keySize, publicKey[0], publicKey[1]))
|
2019-10-05 05:14:13 +00:00
|
|
|
|
|
|
|
print("Writing private key to file %s_privkey.txt..." % name)
|
2020-01-18 12:24:33 +00:00
|
|
|
with open("%s_privkey.txt" % name, "w") as out_file:
|
|
|
|
out_file.write("{},{},{}".format(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()
|