Last active
December 31, 2015 12:19
-
-
Save yogeesh/7985472 to your computer and use it in GitHub Desktop.
RSA encrypter and decrypter functionality in python.
Not written for use in real life situation. You can use it in CTF's and mainly for learning purpose.
Dont duplicate this copy, just share it :)
Suggestion's and comments are welcomed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
import math | |
def enc(message, pubkey) : | |
msg = [ord(char) for char in message] | |
e,n = pubkey | |
c = [pow(m, e, n) for m in msg] # c = m**e % n | |
return c | |
def dec(cipher, prikey) : | |
d,n = prikey | |
msg = [pow(c, d, n) for c in cipher] # msg = c**d % n | |
msg = [chr(m) for m in msg] | |
message = ''.join(msg) | |
return message | |
def isprime(num): | |
for x in range(2, int(math.sqrt(num)+1) ): | |
if(num % x == 0): | |
return 0 | |
return 1 | |
# Starts here :p | |
# Generating two random prime numbers such that their product should be more than meassage | |
while (1): | |
p1 = random.randint(20,50)# bigger the number more GOOD :D | |
if(isprime(p1)): | |
break | |
print 'p1 ', p1 | |
while (1): | |
p2 = random.randint(20,50) # bigger the number more GOOD :D | |
if(isprime(p2)): | |
break | |
print 'p2 ', p2 | |
n = p1 * p2 | |
phi_n = (p1-1)*(p2-1) | |
print 'phi_n ', phi_n | |
#Choosing a prime number for e leaves us only to check that e is not a divisor of 3120 | |
e = 3 | |
while (1): | |
if( isprime(e) and (phi_n % e != 0)): | |
break | |
e = e+2 | |
print 'e ', e | |
#d = (k * phi_n + 1)/ e | |
for d in range (1,phi_n): | |
if(d*e % phi_n == 1): | |
break | |
print 'd ', d | |
pubkey = (e, n) | |
prikey = (d, n) | |
msg = raw_input("Enter the bloody string you want to encrypt: ") | |
print msg | |
cipher = enc(msg, pubkey) | |
for c in cipher : print c, | |
decipher = dec(cipher, prikey) | |
print '\n', decipher |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment