Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ashutosh1206
GitHub Repository: ashutosh1206/crypton
Path: blob/master/RSA-encryption/Intro-Challenges/Challenge-14/encrypt.py
1402 views
1
#!/usr/bin/env python
2
from Crypto.PublicKey import *
3
from Crypto.Util.number import *
4
import os, sys
5
6
class Unbuffered(object):
7
def __init__(self, stream):
8
self.stream = stream
9
def write(self, data):
10
self.stream.write(data)
11
self.stream.flush()
12
def writelines(self, datas):
13
self.stream.writelines(datas)
14
self.stream.flush()
15
def __getattr__(self, attr):
16
return getattr(self.stream, attr)
17
18
sys.stdout = Unbuffered(sys.stdout)
19
20
def _encrypt(message, e, n):
21
m = bytes_to_long(message)
22
return long_to_bytes(pow(m, e, n))
23
24
def genkey(size):
25
p = getPrime(size/2)
26
q = getPrime(size/2)
27
e = getPrime(17)
28
phin = (p-1)*(q-1)
29
d = inverse(e, phin)
30
n = p*q
31
return (p, q, e, d, phin, n)
32
33
if __name__ == "__main__":
34
p, q, e, d, phin, n = genkey(1024)
35
print "Welcome to RSA encryption oracle!"
36
for i in range(12):
37
print "RSA service"
38
print "[1] Encrypt"
39
print "[2] Give me N"
40
option = int(raw_input("Enter your choice: "))
41
if option == 1:
42
try:
43
message = raw_input("Enter the message you want to encrypt (in hex): ").decode("hex")
44
except:
45
print "Enter proper hex chars"
46
exit(0)
47
ct = _encrypt(message, e, n)
48
print "Here take your ciphertext (in hex): ", ct.encode("hex")
49
print "\n\n"
50
elif option == 2:
51
try:
52
mod_val = int(raw_input("Enter the value of modulus: "))
53
except Exception as es:
54
print "[+] Exception: ", es
55
if mod_val == n:
56
print "Voila! You solved the challenge!"
57
else:
58
print "Nice try! But the answer is incorrect!"
59
else:
60
print "Enter proper value of choice"
61
print "Exiting..."
62
63