Python/ciphers/rsa_key_generator.py

55 lines
1.7 KiB
Python
Raw Normal View History

2016-09-06 12:23:48 +00:00
import random, sys, os
import rabin_miller as rabinMiller, cryptomath_module as cryptoMath
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(
'"%s_pubkey.txt" or "%s_privkey.txt" already exists. \nUse a different name or delete these files and re-run this program.'
% (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)
with open("%s_pubkey.txt" % name, "w") as fo:
fo.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)
with open("%s_privkey.txt" % name, "w") as fo:
fo.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()