Working key pair generation, encryption and decryption
TODO: - Clean up - Split into methods - Save a key pair in a file (interactivly)?
This commit is contained in:
parent
1a591cc75e
commit
1993551a59
38
rsa.py
38
rsa.py
@ -5,14 +5,48 @@
|
|||||||
|
|
||||||
import math
|
import math
|
||||||
import os
|
import os
|
||||||
|
import decimal
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
|
|
||||||
#Prime of size 32 bit random
|
#Primes of size 32 bit random
|
||||||
print(getPrime(32))
|
#resulting in a 64-bit key mod
|
||||||
|
p = getPrime(32)
|
||||||
|
print("p: ", p)
|
||||||
|
q = getPrime(32)
|
||||||
|
print("q: ", q)
|
||||||
|
n = p*q
|
||||||
|
print("n: ", n)
|
||||||
|
print("%d bit key" % n.bit_length())
|
||||||
|
|
||||||
|
#lamda(n) = LCM(p-1, q-1)
|
||||||
|
#Since LCM(a,b) = ab/GCD(a,b)
|
||||||
|
#gcd = math.gcd(p-1, q-1)
|
||||||
|
#print("GCD: ", gcd)
|
||||||
|
#lcm = abs((p-1) * (q-1)) / gcd
|
||||||
|
#print("LCM: ", lcm)
|
||||||
|
phi = (p-1)*(q-1)
|
||||||
|
print("phi: ", phi)
|
||||||
|
#e exponant should be 1 < e < lamda(n) and GCD(e, lamda(n)) = 1 (coprime)
|
||||||
|
# recommended value is 65,537
|
||||||
|
e = 65537
|
||||||
|
d = pow(e,-1,phi)
|
||||||
|
print("d: ", d)
|
||||||
|
print("--------------")
|
||||||
|
print("public key (%d, %d)" % (n,e) )
|
||||||
|
|
||||||
|
msg_text = "Hello"
|
||||||
|
msg_number_form = int.from_bytes(msg_text.encode(),"little")
|
||||||
|
print("Message: %s or %d" % (msg_text, msg_number_form))
|
||||||
|
|
||||||
|
msg_encrypted_number_form = pow(msg_number_form, e, n)
|
||||||
|
print("Encrypted msg: ", msg_encrypted_number_form)
|
||||||
|
msg_decrypted_number_form = pow(msg_encrypted_number_form, d, n)
|
||||||
|
print("Decrypted msg: ", msg_decrypted_number_form)
|
||||||
|
|
||||||
def getPrime(bits):
|
def getPrime(bits):
|
||||||
while True:
|
while True:
|
||||||
|
#Byte order "little" or "big" does not matter here since we want a random number from os.urandom()
|
||||||
x = int.from_bytes(os.urandom(int(bits/8)),"little")
|
x = int.from_bytes(os.urandom(int(bits/8)),"little")
|
||||||
if isPrime(x):
|
if isPrime(x):
|
||||||
return x
|
return x
|
||||||
|
Loading…
Reference in New Issue
Block a user