Path: blob/master/RSA-encryption/Attack-LSBit-Oracle/encrypt.py
1402 views
#!/usr/bin/env python1from Crypto.PublicKey import *2from Crypto.Util.number import *3import os, sys45class Unbuffered(object):6def __init__(self, stream):7self.stream = stream8def write(self, data):9self.stream.write(data)10self.stream.flush()11def writelines(self, datas):12self.stream.writelines(datas)13self.stream.flush()14def __getattr__(self, attr):15return getattr(self.stream, attr)1617sys.stdout = Unbuffered(sys.stdout)1819def _encrypt(message, e, n):20m = bytes_to_long(message)21return long_to_bytes(pow(m, e, n))2223def _decrypt(ciphertext, d, n):24ct = bytes_to_long(ciphertext)25return long_to_bytes(pow(ct, d, n) % 2)2627def genkey(size):28p = getPrime(size/2)29q = getPrime(size/2)30e = 6553731phin = (p-1)*(q-1)32d = inverse(e, phin)33n = p*q34return (p, q, e, d, phin, n)3536if __name__ == "__main__":37p, q, e, d, phin, n = genkey(1024)38# Make any flag file to run this challenge39flag = open("flag").read().strip()40print "Welcome to RSA encryption oracle!"41print "Here take your flag (in hex): ", _encrypt(flag, e, n).encode("hex")42print "Here take modulus: ", n43for i in range(1050):44print "RSA service"45print "[1] Encrypt"46print "[2] Decrypt"47option = int(raw_input("Enter your choice: "))48if option == 1:49try:50message = raw_input("Enter the message you want to encrypt (in hex): ").decode("hex")51except:52print "Enter proper hex chars"53exit(0)54ct = _encrypt(message, e, n)55print "Here take your ciphertext (in hex): ", ct.encode("hex")56print "\n\n"57elif option == 2:58try:59ciphertext = raw_input("Enter the ciphertext you want to decrypt (in hex): ").decode("hex")60except:61print "Enter proper hex chars"62exit(0)63msg = _decrypt(ciphertext, d, n)64print "Here take your plaintext (in hex): ", msg.encode("hex")65print "\n\n"66else:67print "Enter a valid option!"68print "Exiting..."697071