def secure_two_party_computation(): global x,y,N e,d,n = rsa.generate_keys() # e,d,n = 7,23,55 print("keys (e,d,n) : ", e,d,n) while(n < 1024): time.sleep(1) e,d,n = rsa.generate_keys() print("Reselected keys (e,d,n) : ", e,d,n) m1 = r.randint(512,1024) # m1 = 39 print("m1 : ",m1) # size_of_m1 = math.log(m1, 2) # print("size of m1 : ",size_of_m1) c = rsa.encrypt(e, n, m1) c1 = c - x print("c1 : ",c1) m2 = [] for i in range(1,N+1): m2.append(rsa.decrypt(d, n, c1+i)) # print("m2 : ",m2) p = pick_prime() # p = 31 selected = 0 # print("Prime list : ",p) for i in range(len(p)): selected = p[i] z = compute_zlist(selected, N, m2) # print("z : ",z) f = condition_check(z,selected) if(f): break else: continue # z = [] # z = compute_zlist(p, N, m2) # print("z : ",z) # while(not condition_check(z, p)): # print(condition_check(z, p)) # time.sleep(1) # p = pick_prime(m1) # z = compute_zlist(p, N, m2) for i in range(y, len(z)): z[i] += 1 # print(p) if (z[x-1] % selected) == (m1 % selected): return "x <= y" else: return "x > y"
def start_client(host, port): global client_socket client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: client_socket.connect((host, port)) except: print("Could not connect to {}:{}".format(host, port)) os.kill(os.getpid(), signal.SIGINT) print("Connected to {}".format(host)) # Perform RSA handshake keys = rsa.generate_keys() handshake = json.dumps({'type': 'handshake', 'payload': keys['public']}) server_handshake = json.loads(client_socket.recv(1024).decode('utf-8')) client_socket.send(handshake.encode('utf-8')) server_key = server_handshake['payload'] threading.Thread(target=output_thread, args=(host, keys['private'])).start() threading.Thread(target=input_thread, args=(server_key, )).start()
def main(): length = 32 if len(sys.argv) > 1: length = int(sys.argv[1]) e, d, n = rsa.generate_keys(length) while True: encrypt = raw_input('\nChoose method:\n1. Encrypt binary\n2. ' 'Encrypt characters\n3. Decrypt binary\n4. Decrypt characters\n5. Exit\n') if encrypt == '5': break m = raw_input('Enter plaintext or ciphertext: ') if encrypt == '1' or encrypt == '3': binary = True for c in m: if c is not "0" and c is not "1": binary = False if binary: parsed = bitarray(m) m = 0 for b in parsed: m = (m << 1) | b else: print 'Input is not binary!' elif encrypt == '4': m = m.split(',') m = [bitarray(c) for c in m] if encrypt == '1': cipher = rsa.encrypt(e, n, int(m)) print 'Cipher: %d' % cipher print 'Cipher binary: %s' % bitarray("{0:b}".format(cipher)).to01() elif encrypt == '2': cipher = rsa.encrypt_str(e, n, m) cipher_str = [str(c) for c in cipher] print 'Cipher: %s' % ''.join(cipher_str) binary_str = [bitarray("{0:b}".format(int(number))).to01() for number in cipher_str] print 'Cipher binary: %s' % ','.join(binary_str) elif encrypt == '3': plaintext = rsa.decrypt(d, n, m) print 'Plaintext: %d' % plaintext b = bitarray("{0:b}".format(plaintext)) print 'Plaintext binary: %s' % b.to01() elif encrypt == '4': numberic_cipher = [] for c in m: i = 0 for b in c: i = (i << 1) | b numberic_cipher.append(i) decrypted_list = rsa.decrypt_list(d, n, numberic_cipher) print ''.join([chr(c) for c in decrypted_list])
def __init__(self): HOST = '127.0.0.1' PORT = 33000 self.BUFSIZ = 1024 ADDR = (HOST, PORT) self.client_socket = socket(AF_INET, SOCK_STREAM) self.client_socket.connect(ADDR) self.available_messages = [] self.PUBLIC_KEY, self.PRIVATE_KEY = rsa.generate_keys()
def __init__(self, host, port): self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.keys = rsa.generate_keys() try: self.s.bind((host, port)) except socket.error: print("Could not bind to port {}".format(port)) sys.exit() self.s.listen(10) print("Started server on {}:{}".format(host, port)) self.main_loop()
def main(): parser = argparse.ArgumentParser(description='Connect to RSA encrypted chat server') parser.add_argument('-mprime', dest='m', action='store', default=-1, help='Mth prime to select') parser.add_argument('-nprime', dest='n', action='store', default=-1, help='Nth prime to select') args = parser.parse_args() m = int(args.m) n = int(args.n) if m == -1 or n == -1: parser.print_help() return keys = rsa.generate_keys(m=m, n=n) print("Public Key: {}\nPrivate Key: {}\n".format(keys['public'], keys['private']))
def main(): p = 9967 q = 9973 print("Use default p and q (y/n)") choice = input(">>>") if choice == "n": p, q = input_p_and_q() public_key, private_key = rsa.generate_keys(p, q) n = p * q phi = (p - 1) * (q - 1) while True: print() print("p :", p) print("q :", q) print("n :", n) print("phi :", phi) print("Public key :", public_key[0]) print("Private key :", private_key[0]) print() print("Enter message") message = input(">>>") if message == "~": exit(0) encrypted_message = rsa.encrypt(numbers_from_letters(message), public_key) decrypted_message = rsa.encrypt(encrypted_message, private_key) print("Message :", message) print("Message as bytes array :", numbers_from_letters(message)) print("Encrypted message as numbers array :", encrypted_message) print("Decrypted message as numbers array :", decrypted_message) print("Decrypted message :", "".join(letters_from_numbers(decrypted_message))) input()
def main(): p = 9967 q = 9973 print("Use default p and q (y/n)") choice = input(">>>") if choice == "n": p, q = input_p_and_q() public_key, private_key = rsa.generate_keys(p, q) n = p * q phi = (p - 1) * (q - 1) while True: print() print("p :", p) print("q :", q) print("n :", n) print("phi :", phi) print("Public key :", public_key[0]) print("Private key :", private_key[0]) print() print("Enter message") message = input(">>>") if message == "~": exit(0) message_as_numbers = numbers_from_letters(message) signature = digital_signature.create_signature(message_as_numbers, private_key) message_with_sign = message_as_numbers, signature is_actual_signature, hash1, hash2 = digital_signature.check_signature( message_with_sign, public_key) print("Signature :", signature) print("Hash from signature and public key :", hash1) print("Hash from message and hash function :", hash2) print("Is actual signature :", is_actual_signature) input()
def plot_crypt(max_key_length, trials): key_lengths = range(8, max_key_length + 1) encryption_times = [] for key_length in key_lengths: print('Computing key length', key_length) key_length_time = 0 for _ in range(trials): e, _, n = generate_keys(key_length) time_before = time() crypt(n - 1, (e, n)) time_after = time() key_length_time += time_after - time_before encryption_times.append(key_length_time / trials) pyplot.plot(key_lengths, encryption_times) pyplot.title('Encryption Time vs. Key Length') pyplot.xlabel('Key Length (in bits)') pyplot.ylabel('Encryption Time (in seconds)') pyplot.show()
def plot_crack(max_key_length, trials): key_lengths = range(8, max_key_length + 1) crack_times = [] for key_length in key_lengths: print('Computing key length', key_length) key_length_time = 0 for _ in range(trials): e, d, n = generate_keys(key_length) time_before = time() private_key = math_attack(e, n) time_after = time() if d != private_key: raise RuntimeError key_length_time += time_after - time_before crack_times.append(key_length_time / trials) pyplot.plot(key_lengths, crack_times) pyplot.title('Math Attack Time vs. Key Length') pyplot.xlabel('Key Length (in bits)') pyplot.ylabel('Encryption Time (in seconds)') pyplot.show()
import rsa if __name__ == '__main__': public, private = rsa.generate_keys() print ("Your public key is ", public ," and your private key is ", private) message = input("Enter a message to encrypt with your private key: ") encrypted_msg, cipher = rsa.encrypt(private, message) print ("Your encrypted message is: {}".format(encrypted_msg)) print("---------------------") print ("Decrypting message with public key ", public ," . . .") print ("Your message is: ") print (rsa.decrypt(public, cipher))
def proc(self, my_msg, peer_msg): self.out_msg = '' self.set_indexing() #============================================================================== # Once logged in, do a few things: get peer listing, connect, search # And, of course, if you are so bored, just go # This is event handling instate "S_LOGGEDIN" #============================================================================== if self.state == S_LOGGEDIN: # todo: can't deal with multiple lines yet if len(my_msg) > 0: if my_msg == 'q': self.out_msg += 'See you next time!\n' pkl.dump(self.indices[self.me], open(self.me + '.idx', 'wb')) del self.indices[self.me] self.state = S_OFFLINE print('here - 88') elif my_msg == 'time': mysend(self.s, json.dumps({"action": "time"})) time_in = json.loads(myrecv(self.s))["results"] self.out_msg += "Time is: " + time_in elif my_msg == 'who': mysend(self.s, json.dumps({"action": "list"})) logged_in = json.loads(myrecv(self.s))["results"] self.out_msg += 'Here are all the users in the system:\n' self.out_msg += logged_in elif my_msg[0] == 'c': peer = my_msg[1:] peer = peer.strip() if self.connect_to(peer) == True: self.state = S_CHATTING self.out_msg += 'Connect to ' + peer + '. Chat away!\n\n' self.out_msg += '-----------------------------------\n' else: self.out_msg += 'Connection unsuccessful\n' elif my_msg[0] == '?': term = my_msg[1:].strip() rslt = '\n'.join( [x[-1] for x in self.indices[self.me].search(term)]) #mysend(self.s, json.dumps({"action":"search", "target":term})) #search_rslt = json.loads(myrecv(self.s))["results"].strip() if (len(rslt)) > 0: self.out_msg += rslt + '\n\n' else: self.out_msg += '\'' + term + '\'' + ' not found\n\n' elif my_msg[0] == 'p' and my_msg[1:].isdigit(): poem_idx = my_msg[1:].strip() mysend(self.s, json.dumps({ "action": "poem", "target": poem_idx })) poem = json.loads(myrecv(self.s))["results"] if (len(poem) > 0): self.out_msg += poem + '\n\n' else: self.out_msg += 'Sonnet ' + poem_idx + ' not found\n\n' else: self.out_msg += menu if len(peer_msg) > 0: try: peer_msg = json.loads(peer_msg) except Exception as err: self.out_msg += " json.loads failed " + str(err) return self.out_msg if peer_msg["action"] == "connect": # ----------your code here------# self.peer = peer_msg["from"] self.out_msg += 'Request from ' + self.peer + '\n' self.out_msg += 'You are connected with ' + self.peer self.out_msg += '. Chat away!\n\n' self.out_msg += '------------------------------------\n' self.state = S_CHATTING # ----------end of your code----# #============================================================================== # Start chatting, 'bye' for quit # This is event handling instate "S_CHATTING" #============================================================================== elif self.state == S_CHATTING: if self.public_key == (): self.public_key, self.private_key = rsa.generate_keys() mysend( self.s, json.dumps({ "action": "key", "public key": self.public_key })) if len(my_msg) > 0: # my stuff going out msg = rsa.encrypt(my_msg, self.private_key) said2 = text_proc(my_msg, self.me) self.indices[self.me].add_msg_and_index(said2) mysend( self.s, json.dumps({ "action": "exchange", "from": self.me, "message": msg })) self.out_msg += "[" + self.me + "] " + my_msg + "\n" if my_msg == 'bye': mysend(self.s, json.dumps({"action": "reset"})) self.disconnect() self.state = S_LOGGEDIN self.peer = '' self.reset_keys() if len(peer_msg) > 0: # peer's stuff, coming in # ----------your code here------# peer_msg = json.loads(peer_msg) if peer_msg["action"] == "connect": self.out_msg += "(" + peer_msg["from"] + " joined)\n" elif peer_msg["action"] == "disconnect": self.state = S_LOGGEDIN elif peer_msg["action"] == "key": self.peer_key = peer_msg["public key"] elif peer_msg["action"] == "exchange": msg = rsa.encrypt(peer_msg["message"], self.peer_key) self.out_msg += "Encrypted message:" + peer_msg[ 'message'] + '\n' self.out_msg += "[" + peer_msg["from"] + "]" + msg said2 = text_proc(msg, peer_msg["from"]) self.indices[self.me].add_msg_and_index(said2) elif peer_msg["action"] == "reset": self.reset_keys() # ----------end of your code----# if self.state == S_LOGGEDIN: # Display the menu again self.out_msg += menu #============================================================================== # invalid state #============================================================================== else: self.out_msg += 'How did you wind up here??\n' print_state(self.state) return self.out_msg
import rsa import elgamal # Note: RSA will take a while (5mins+) to complete on a non-workstation PC. # RSA ################################################################ print("RSA digital signature demo.\n") message = 123456 # sender generate keys keys = rsa.generate_keys(5563, 3821, 9623) print(keys) # sender generates message signature s = rsa.sign(keys['n'], keys['d'], message) print("Signature:", s) # receiver verifies the signiature and message verified = rsa.verify_signature(keys['n'], keys['e'], s, message) print("Message matches signature:", verified) # ElGamal ############################################################# print("ElGamal digital signature demo.\n") message = 4567 # sender generate keys keys = elgamal.generate_keys(7331, 3411, 41) print("Keys:", keys, "\n")
parser = argparse.ArgumentParser() parsers = parser.add_subparsers(dest='command') generate_keys_parser = parsers.add_parser('generate_keys') generate_keys_parser.add_argument('seed_length', type=int) crypt_parser = parsers.add_parser('crypt', aliases=['encrypt', 'decrypt']) crypt_parser.add_argument('key', type=int, nargs=2) crypt_parser.add_argument('message', type=int) crack_parser = parsers.add_parser('crack') crack_parser.add_argument('key', type=int, nargs=2) plot_parser = parsers.add_parser('plot') plot_parser.add_argument('operation', type=str, choices=['crypt', 'crack']) plot_parser.add_argument('max_key_length', type=int) plot_parser.add_argument('trials', type=int) args = parser.parse_args() if args.command == 'generate_keys': print(generate_keys(args.seed_length)) elif args.command == 'encrypt' or args.command == 'decrypt': print(crypt(args.message, args.key)) elif args.command == 'crack': print(math_attack(*args.key)) elif args.command == 'plot': if args.operation == 'crypt': plot_crypt(args.max_key_length, args.trials) if args.operation == 'crack': plot_crack(args.max_key_length, args.trials) else: raise argparse.ArgumentTypeError('Invalid command')
def generate_keys(): public, private = rsa.generate_keys() print('Public key: \n e = \n' + str(public[0]) + '\n n = \n' + str(public[1])) print('Private key: \n d = \n' + str(private[0]) + '\n n = \n' + str(private[1]))
import f_s def get_args(): import argparse parser = argparse.ArgumentParser() parser.add_argument('type', choices=['rsa', 'elgamal', 'f_s']) parser.add_argument('bit_lenght', choices=['128', '256', '512', '1024', '2048']) parser.add_argument('key_name') return parser.parse_args() if __name__ == "__main__": args = get_args() bitLen = int(args.bit_lenght) if args.type == 'rsa': (e, n), (d, n) = rsa.generate_keys(bitLen) with open(args.key_name + '_public', 'w') as p: p.write(str(e) + "\n") p.write(str(n)) with open(args.key_name + '_private', 'w') as p: p.write(str(d) + "\n") p.write(str(n)) print "keys {0}_public and {0}_private {1} succesfully generated".format(args.key_name, bitLen) if args.type == 'elgamal': (p, g, y), (p, x) = elgamal.generate_keys(bitLen) with open(args.key_name + '_public', 'w') as f: f.write(str(p) + "\n") f.write(str(g) + "\n") f.write(str(y)) with open(args.key_name + '_private', 'w') as f:
import rsa def print_private(): fd = open("private_key.pem", "r") print(fd.read()) print("\n\n") fd.close() def print_public(): fd = open("public_key.pem", "r") print(fd.read()) print("\n\n") fd.close() #the plain text you want to cipher plain_text = input("Enter plain text: ") cipher_text = rsa.encrypt("public_key", plain_text.encode('utf-8')) print("The ciphertext is: " + cipher_text) print("\n") #Return it to the original stat plain_text = rsa.decrypt(cipher_text) print("The plaintext again: " + plain_text) rsa.generate_keys() print_private() print_public()
import rsa alice = "Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, 'and what is the use of a book,' thought Alice 'without pictures or conversation?'" hg1 = "Space is big. Really big. You just won't believe how vastly hugely mind-bogglingly big it is. I mean, you may think it's a long way down the road to the chemist, but that's just peanuts to space. Listen..." hg2 = "The story so far:\n\tIn the beginning the Universe was created.\n\tThis has made a lot of people very angry and been widely regarded as a bad move.\n\tMany races believe that it was created by some sort of god, though the Jatravartid people of Viltvodle VI believe that the entire Universe was in fact sneezed out of the nose of a being called the Great Green Arkleseizure." hg3 = "The regular early morning yell of horror was the sound of Arthur Dent waking up and suddenly remembering where he was.\n\tIt wasn't just that the cave was cold, it wasn't just that it was damp and smelly. It was that the cave was in the middle of Islington and there wasn't a bus due for two million years." hobbit = "In a hole in the ground there lived a hobbit. Not a nasty, dirty, wet hole, filled with the ends of worms and an oozy smell, nor yet a dry, bare, sandy hole with nothing in it to sit down on or to eat: it was a hobbit-hole, and that means comfort." holmes = "Mr. Sherlock Holmes, who was usually very late in the mornings, save upon those not infrequent occasions when he was up all night, was seated at the breakfast table." pp2 = "Mr. Bennet was among the earliest of those who waited on Mr. Bingley. He had always intended to visit him, though to the last always assuring his wife that he should not go; and till the evening after the visit was paid she had no knowledge of it. It was then disclosed in the following manner. Observing his second daughter employed in trimming a hat, he suddenly addressed her with:\n\t\"I hope Mr. Bingley will like it, Lizzy.\"" rime = "It is an ancient Mariner,\nAnd he stoppeth one of three.\n\"By thy long grey beard and glittering eye,\nNow wherefore stopp'st thou me?" study = "In the year 1878 I took my degree of Doctor of Medicine of the University of London, and proceeded to Netley to go through the course prescribed for surgeons in the army. Having completed my studies there, I was duly attached to the Fifth Northumberland Fusiliers as Assistant Surgeon. The regiment was stationed in India at the time, and before I could join it, the second Afghan war had broken out. On landing at Bombay, I learned that my corps had advanced through the passes, and was already deep in the enemy's country. I followed, however, with many other officers who were in the same situation as myself, and succeeded in reaching Candahar in safety, where I found my regiment, and at once entered upon my new duties." ri_public, ri_private = rsa.generate_keys(1031, 1973) rsa.test_encryption((ri_public, ri_private), "Share & Enjoy") message = r"""rob:~/iCloud/MATH4011$ julia _ _ _ _(_)_ | Documentation: https://docs.julialang.org (_) | (_) (_) | _ _ _| |_ __ _ | Type "?" for help, "]?" for Pkg help. | | | | | | |/ _` | | | | |_| | | | (_| | | Version 1.3.1 (2019-12-30) _/ |\__'_|_|_|\__'_| | Official https://julialang.org/ release |__/ | julia> using Primes julia> using Dates julia> begin t0 = now()
password = '******' sep = '|' output = '' N = 100 s = socket.socket() s.connect((ip, port)) vals = [] if (os.path.exists(userid)): keys = open(userid, 'r') vals = json.load(keys) keys.close() # print(vals) else: e, d, n = rsa.generate_keys() while (n < 1024): e, d, n = rsa.generate_keys() vals = [e, d, n] keys = open(userid, 'w') json.dump(vals, keys) keys.close() # print(vals) public_key = [] public_key = str(vals[0]) + ',' + str(vals[2]) register(s, userid, password, public_key) if userid == 'c1': x = int(val)
message = "Cryptocurrencies continue to grow in price and size. Knowledge about Bitcoin, Litecoin, Ethereum, and others has spread through the entire world. Cryptocurrencies are providing such features and tools that simplify our lives. They are changing the way things work. Some people fear the changes. But changes are not always bad. Cryptocurrencies are modifying our lives, and the way industries develop. There’s no doubt that cryptocurrencies are disrupting and affecting the global economy in many ways." print("Message:", message) # Sender hashes the message then converts to decimal (from hex) msg_hash = hashlib.md5(message.encode('utf-8')).hexdigest() print("MD5 message Hash:", msg_hash) msg_hash = int(msg_hash, 16) print("Hash as decimal:", msg_hash) # Sender generates keys p = 278966591577398076867954212605012776073 q = 467207331195239613378791200749462989467 e = 41 keys = rsa.generate_keys(p, q, e) print("Keys:", keys) # Sender signs the message with the private key # s = rsa.sign(keys['n'], keys['d'], msg_hash) # Used wolfram alpha to find signature s = m^d mod n, python is way too slow # for this operation. s = 126798804286385130870848966135941566606057839336135951340495096277825470279796 print("Signature:", s) # Receiver verifies the signature and message verify = rsa.verify_signature(keys['n'], keys['e'], s, msg_hash) print("Message matches signature:", verify) # Receiver hashes the original message to check it matches the given hash