├── README.md └── main.py /README.md: -------------------------------------------------------------------------------- 1 | # RSA-Implementation-in-Python 2 | This is a simple but slow implementation of the RSA Algorithm in Python. 3 | I made this for Studying purposes in my 2nd Semester. 4 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Created on 07.09.2016 3 | 4 | @author: Marius 5 | ''' 6 | 7 | import random 8 | max_PrimLength = 1000000000000 9 | 10 | ''' 11 | calculates the modular inverse from e and phi 12 | ''' 13 | def egcd(a, b): 14 | if a == 0: 15 | return (b, 0, 1) 16 | else: 17 | g, y, x = egcd(b % a, a) 18 | return (g, x - (b // a) * y, y) 19 | 20 | ''' 21 | calculates the gcd of two ints 22 | ''' 23 | def gcd(a, b): 24 | while b != 0: 25 | a, b = b, a % b 26 | return a 27 | 28 | ''' 29 | checks if a number is a prime 30 | ''' 31 | def is_prime(num): 32 | if num == 2: 33 | return True 34 | if num < 2 or num % 2 == 0: 35 | return False 36 | for n in range(3, int(num**0.5)+2, 2): 37 | if num % n == 0: 38 | return False 39 | return True 40 | 41 | def generateRandomPrim(): 42 | while(1): 43 | ranPrime = random.randint(0,max_PrimLength) 44 | if is_prime(ranPrime): 45 | return ranPrime 46 | 47 | def generate_keyPairs(): 48 | p = generateRandomPrim() 49 | q = generateRandomPrim() 50 | 51 | n = p*q 52 | print("n ",n) 53 | '''phi(n) = phi(p)*phi(q)''' 54 | phi = (p-1) * (q-1) 55 | print("phi ",phi) 56 | 57 | '''choose e coprime to n and 1 > e > phi''' 58 | e = random.randint(1, phi) 59 | g = gcd(e,phi) 60 | while g != 1: 61 | e = random.randint(1, phi) 62 | g = gcd(e, phi) 63 | 64 | print("e=",e," ","phi=",phi) 65 | '''d[1] = modular inverse of e and phi''' 66 | d = egcd(e, phi)[1] 67 | 68 | '''make sure d is positive''' 69 | d = d % phi 70 | if(d < 0): 71 | d += phi 72 | 73 | return ((e,n),(d,n)) 74 | 75 | def decrypt(ctext,private_key): 76 | try: 77 | key,n = private_key 78 | text = [chr(pow(char,key,n)) for char in ctext] 79 | return "".join(text) 80 | except TypeError as e: 81 | print(e) 82 | 83 | def encrypt(text,public_key): 84 | key,n = public_key 85 | ctext = [pow(ord(char),key,n) for char in text] 86 | return ctext 87 | 88 | if __name__ == '__main__': 89 | public_key,private_key = generate_keyPairs() 90 | print("Public: ",public_key) 91 | print("Private: ",private_key) 92 | 93 | ctext = encrypt("Hello World",public_key) 94 | print("encrypted =",ctext) 95 | plaintext = decrypt(ctext, private_key) 96 | print("decrypted =",plaintext) 97 | --------------------------------------------------------------------------------