Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ashutosh1206
GitHub Repository: ashutosh1206/crypton
Path: blob/master/RSA-encryption/Attack-LSBit-Oracle/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 _decrypt(ciphertext, d, n):
25
ct = bytes_to_long(ciphertext)
26
return long_to_bytes(pow(ct, d, n) % 2)
27
28
def genkey(size):
29
p = getPrime(size/2)
30
q = getPrime(size/2)
31
e = 65537
32
phin = (p-1)*(q-1)
33
d = inverse(e, phin)
34
n = p*q
35
return (p, q, e, d, phin, n)
36
37
if __name__ == "__main__":
38
p, q, e, d, phin, n = genkey(1024)
39
# Make any flag file to run this challenge
40
flag = open("flag").read().strip()
41
print "Welcome to RSA encryption oracle!"
42
print "Here take your flag (in hex): ", _encrypt(flag, e, n).encode("hex")
43
print "Here take modulus: ", n
44
for i in range(1050):
45
print "RSA service"
46
print "[1] Encrypt"
47
print "[2] Decrypt"
48
option = int(raw_input("Enter your choice: "))
49
if option == 1:
50
try:
51
message = raw_input("Enter the message you want to encrypt (in hex): ").decode("hex")
52
except:
53
print "Enter proper hex chars"
54
exit(0)
55
ct = _encrypt(message, e, n)
56
print "Here take your ciphertext (in hex): ", ct.encode("hex")
57
print "\n\n"
58
elif option == 2:
59
try:
60
ciphertext = raw_input("Enter the ciphertext you want to decrypt (in hex): ").decode("hex")
61
except:
62
print "Enter proper hex chars"
63
exit(0)
64
msg = _decrypt(ciphertext, d, n)
65
print "Here take your plaintext (in hex): ", msg.encode("hex")
66
print "\n\n"
67
else:
68
print "Enter a valid option!"
69
print "Exiting..."
70
71