def run(self): global Globalvariable while 1: message_recu = self.connexion.recv(1024).decode("Utf8") if message_recu[0:14] == "##Rsapubkeyis#": if not Globalvariable['RSA_Recieved']: message = message_recu[14:].split("#") Globalvariable['OtherRsaE'], Globalvariable[ 'OtherRsaN'] = int(message[0]), int(message[1]) self.connexion.send("##YesRsa".encode("Utf8")) Rsa = RSA() Globalvariable["EncRC4Key"] = Rsa.crypt( Globalvariable["OtherRsaE"], Globalvariable["OtherRsaN"], Globalvariable["RC4Key"]) Globalvariable['RSA_Recieved'] = True color_print( "Public Anahtarı -->" + str(Globalvariable["OtherRsaE"]) + str(Globalvariable["OtherRsaN"]), 'red') color_print( "RC4 Private Anahtarı -->" + Globalvariable["RC4Key"], 'red') color_print( "Şifrelenmiş Anahtar -->" + str(Globalvariable["EncRC4Key"]), 'red') else: self.connexion.send("##YesRsa".encode("Utf8")) elif message_recu == "##YesRsa": Globalvariable['RSA_Sent'] = True elif message_recu[:6] == "##RC4#": if Globalvariable["OtherRC4"] == "": Rsa = RSA() Globalvariable["OtherRC4"] = Rsa.decrypt( Globalvariable["d"], Globalvariable["n"], int(message_recu[6:])) self.connexion.send("##YesRC4".encode("Utf8")) else: self.connexion.send("##YesRC4".encode("Utf8")) elif message_recu == "##YesRC4": if not Globalvariable["RC4_sent"]: Globalvariable["RC4_sent"] = True elif Globalvariable['RSA_Sent'] and Globalvariable[ 'RSA_Recieved'] and message_recu[ 0: 14] != "##Rsapubkeyis#" and message_recu != "##YesRsa" and message_recu != "##YesRC4": Rc44 = RC4() Rc44.shuffle(str(Globalvariable["OtherRC4"])) message = Rc44.Crypt(message_recu) color_print("Mesaj -->" + message, 'yellow') color_print("Şifrelenmiş Mesaj -->" + message_recu, 'blue')
def calculation(message, n, e, d, p, q, startzustand=[1, 1, 1, 1, 0, 0, 0, 0], verbose=False): ### Alice ### ## 1, a = bitarray(startzustand) start_lfsr_alice = LFSR.lfsr(a, [0, 1, 3, 4]) key = [next(start_lfsr_alice) for _ in range(120)] key = "".join(str(x) for x in startzustand + key) print("--ALICE--------") print("LFSR-Key: {}".format(helper.get_split_string_from_list(list(key)))) ## 2, rsa = RSA(p="", q="", n=n, e=e) if verbose: rsa.print_stats() c_1 = rsa.short_public_exponent_encrypt(int("".join( str(i) for i in startzustand), base=2), verbose=verbose) print("RSA Ciphertext: {}".format(c_1)) ## 3, aes = AES(key) c_2 = aes.encrypt(message, verbose=verbose) print("AES Ciphertext: {}".format(c_2)) ### Bob ### ## 1, rsa = RSA(p=p, q=q, e=e, private_key=d) print("--BOB----------") print("Decryption....") bin_str = bin(rsa.chinese_decrypt(c_1, verbose=verbose))[2:] print("RSA Plaintext: {}".format( helper.get_split_string_from_list(list(bin_str)))) ## 2, a = bitarray(bin_str) start_lfsr_bob = LFSR.lfsr(a, [0, 1, 3, 4]) key_bob = [next(start_lfsr_bob) for _ in range(120)] key_bob = "".join(str(x) for x in list(bin_str) + key_bob) print("LFSR-Key: {}".format( helper.get_split_string_from_list(list(bin_str)))) ## 3, aes = AES(key_bob) corresponding_message = aes.decrypt(c_2, verbose=verbose) print("Message: {}".format(corresponding_message)) return message
def main(): # input as found in Exercise7_in7_to_student_Crowley.txt # first prime p p = 13 # second prime q q = 149 # encryption exponent e e = 257 # encrypted message r r = 1907 print("Running RSA Algorithms to find the RSA Modulus (n), the decryption exponent (d), and the decrypted message (s) for the given input:") print('') print(f"first prime p: {p}") print(f"second prime q: {q}") print(f"encryption exponent e: {e}") print(f"encrypted message r: {r}") print("") print("Initializing RSA class with the given input...") test = RSA(p, q, e) n = test.getPublicKeyPair()[0] d = test._d s = test.decryptMessage(r) print("\nResults") print("~*" * 8) print(f"RSA Modulus n: {n}") print(f"Decryption exponent d (this should be private!): {d}") print(f"Decrypted message s: {s}") print(f"n, d, s = {n}, {d}, {s}") print("~*" * 8)
def test_RSA(inverse, message="The quick brown fox jumps over the lazy dog.", bit_length=4096, e=65537, powmodn=bit_pow_mod_n): print("Generating ", bit_length, "-bit primes...") scheme = RSA(powmodn=powmodn, inverse=inverse, gmp=True) (p, q, n, l, e, d, public_key, private_key) = scheme.generate_keys(bit_length, e) print("\nOriginal plaintext message: ", message) m = string2int(message) print("\nEncrypting message...") c = scheme.rsa_encrypt(m, public_key) ciphertext = int2string(c) print(" Ciphertext: ", ciphertext) print("\nDecrypting message...") [m2, running_time] = rt2(scheme.rsa_decrypt, c, private_key) message2 = int2string(m2) print(" Message decrypted by rsa_decrypt: ", message2) print(" Running time for rsa_decrypt: ", running_time) print("\nDecrypting message using Chinese Remainder Theorem...") [m3, running_time] = rt4(scheme.CRT_rsa_decrypt, c, private_key, p, q) message3 = int2string(m3) print(" Message decrypted by CRT_rsa_decrypt: ", message3) print(" Running time for CRT_rsa_decrypt: ", running_time) return (p, q, n, l, e, d, public_key, private_key, m, c, message, ciphertext)
def create_decrypt_running_time_table(message, e, start, stop, step, trials, inverse, powmodn=bit_pow_mod_n): scheme = RSA(powmodn=powmodn, inverse=inverse) m = string2int(message) print("bit_length,Naïve_fast_exponentiation,CRT_fast_exponentiation") for bit_length in range(start, stop + 1, step): sum_rt = sum_rt_crt = 0 for i in range(trials): (p, q, n, l, e, d, public_key, private_key) = scheme.generate_keys(bit_length, e) c = scheme.rsa_encrypt(m, public_key) # Accumulate naïve recursive running times across trials sum_rt += rt2(scheme.rsa_decrypt, m, private_key)[1] # ditto for CRT sum_rt_crt += rt4(scheme.CRT_rsa_decrypt, c, private_key, p, q)[1] print(bit_length, sum_rt / trials, sum_rt_crt / trials, sep=',')
def initServer(self): self.serverSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.serverSock.bind((self.UDP_IP_ADDRESS, self.UDP_PORT_NO)) self.RSA = RSA() print("Monitorando o endereço: " + self.UDP_IP_ADDRESS + ":" + str(self.UDP_PORT_NO)) threading.Thread(target=self.listenMessages).start()
def disp_ring_data(self): acc=RSA() temp = self.head print("------- Node", temp.key,"-------") for entry in temp.data: print("\t<---->") print(">>FILE NAME:\n", entry.name) print(">>PUBLIC KEY:\n", entry.pubkey) content=entry.content if not users_df[users_df['user']==curr_user][entry.name].isna().values[0]: print("Decrypting with private key...") print(">>CONTENT:\n", acc.decipher_text(content,int(users_df[users_df['user']==curr_user][entry.name].values[0]),entry.pubkey)) else: print("Unable to decrypt without private key.") print(">>ENCRYPTED CONTENT:\n", entry.content) print("\t<---->\n") while(temp.next != self.head): temp = temp.next print("------- Node", temp.key,"-------") for entry in temp.data: print("\t<---->") print(">>FILE NAME:\n", entry.name) print(">>PUBLIC KEY:\n", entry.pubkey) content=entry.content if not users_df[users_df['user']==curr_user][entry.name].isna().values[0]: print("Decrypting with private key...") print(">>CONTENT:\n", acc.decipher_text(content,int(users_df[users_df['user']==curr_user][entry.name].values[0]),entry.pubkey)) else: print("Unable to decrypt without private key.") print(">>ENCRYPTED CONTENT:\n", entry.content) print("\t<---->\n")
def encrypt(self): """ Encryption method. :return: symmetric algorithm object """ # message is encrypted by the given symmetric algorithm if self._algorithm == "AES": sym_alg = AES_DES3(self._key_type, self._message, self._mode) self._path = Constants.aes_secret_key_path else: sym_alg = AES_DES3(self._key_type, self._message, self._mode, False) self._path = Constants.des3_secret_key_path # encryption key, cipher = sym_alg.encrypt() self._cipher = cipher # key is encrypted by the RSA asymmetric algorithm rsa = RSA(self._rsa_key, key, True) crypt_key = rsa.encrypt() self._crypt_key = crypt_key Helper.write_envelope([self._algorithm, 'RSA'], [key, crypt_key], base64.b64encode(cipher), bytes.hex(crypt_key), Constants.envelope_path) return sym_alg
def run_RSA_block(s): r = RSA(16) print(r._p) print(r._q) c = r.encrypt_block(s) print(c.hex()) m = r.decrypt_block(c) assert s.hex() == m.hex()
def __init__(self, n=128): self._n = n self._k0 = 4 self._k1 = 4 self._block_size = self._n - self._k0 - self._k1 self.hash = SHA256() self.rsa = RSA(self._n)
def __init__(self, l): # l is the length of p and q self.l = l self.p = 0 self.q = 0 self.N = 0 self.public_key = 0 self.secret_key = 0 self.rsa = RSA(l)
def run(self): global Globalvariable while 1: message_recu = self.connexion.recv(1024).decode("Utf8") if message_recu[0:14] == "##Rsapubkeyis#": if not Globalvariable['RSA_Recieved']: message = message_recu[14:].split("#") Globalvariable['OtherRsaE'], Globalvariable[ 'OtherRsaN'] = int(message[0]), int(message[1]) self.connexion.send("##YesRsa".encode("Utf8")) Rsa = RSA() Globalvariable["EncRC4Key"] = Rsa.crypt( Globalvariable["OtherRsaE"], Globalvariable["OtherRsaN"], Globalvariable["RC4Key"]) Globalvariable['RSA_Recieved'] = True else: self.connexion.send("##YesRsa".encode("Utf8")) elif message_recu == "##YesRsa": Globalvariable['RSA_Sent'] = True elif message_recu[:6] == "##RC4#": if Globalvariable["OtherRC4"] == "": Rsa = RSA() Globalvariable["OtherRC4"] = Rsa.decrypt( Globalvariable["d"], Globalvariable["n"], int(message_recu[6:])) self.connexion.send("##YesRC4".encode("Utf8")) else: self.connexion.send("##YesRC4".encode("Utf8")) elif message_recu == "##YesRC4": if not Globalvariable["RC4_sent"]: Globalvariable["RC4_sent"] = True elif Globalvariable['RSA_Sent'] and Globalvariable[ 'RSA_Recieved'] and message_recu[ 0: 14] != "##Rsapubkeyis#" and message_recu != "##YesRsa" and message_recu != "##YesRC4": Rc44 = RC4() Rc44.shuffle(str(Globalvariable["OtherRC4"])) message = Rc44.Crypt(message_recu) print("---->>> " + message)
def command_line(): '''Command line wrapper for RSA.py.''' parser = argparse.ArgumentParser( description='Command line interface for RSA encryption') parser.add_argument('-n', '--new-keys', action='store_true', help='Whether or not new keys should be generated.') parser.add_argument('-m', '--message', action='store', type=str, help='Message to be encoded.') parser.add_argument('-c', '--coded-message', action='store', type=str, help='Location of message to be decoded.') parser.add_argument('-k', '--key-files', action='store', type=str, help='TODO') parser.add_argument('-s', '--store-keys', action='store', type=str, help='Desired file location for output of keys') arguments = parser.parse_args() if arguments.new_keys: rsa = RSA(arguments.store_keys) rsa.RSA_keygen() if arguments.message: rsa = RSA(arguments.store_keys) rsa.RSA_encode(arguments.message, arguments.key_files) if arguments.coded_message: rsa = RSA(arguments.store_keys) message = rsa.RSA_decode(arguments.coded_message, arguments.key_files) print(message)
def verify_ciphers(): rsa = RSA() for i in range(100): for cipher_name, ciphers in cipher_list.items(): if not ciphers.verify("test"): print(f"{cipher_name} failed!") break if not rsa.verify("test"): print("RSA failed!") break
def __init__(self, nbits=512, outpath=None, keypath=None): self.a = RSA() if keypath != None: self.a.inputKey(keypath) self.mode = self.a.mode return if outpath == None: outpath = 'PublickeyCipher\\' self.a.generateKey(nbits) self.a.outputPublicKey(outpath) self.a.outputPrivateKey(outpath)
def __init__(self, keySize: int = 1024): self.filePath = "/data/data.dat" self.mainWindow = Tk() self.mainWindow.geometry("630x500") #self.mainWindow.configure(background = "black") self.mainWindow.title("RSA Encrypter-Decrypter") self.mainWindow.grid_columnconfigure(0, minsize=10) self.mainWindow.grid_rowconfigure(10, minsize=20) self.keySize = keySize #Instantiate RSA class, Key will be 1024 by default self.rsa = RSA(self.keySize) self.option = IntVar(0)
def main(): filename = input("Input file name: ") enc_filename = "enc_" + filename dec_filename = "dec_" + filename rsa = RSA(512) print("Start encrypting '{0}' ...".format(filename)) rsa.encrypt(filename, enc_filename) print("Encrypting done. Results saved in file: '{0}'".format(enc_filename)) print("Start decrypting '{0}' ...".format(enc_filename)) rsa.decrypt(enc_filename, dec_filename) print("Decrypting done. Results saved in file: '{0}'".format(dec_filename))
def sign(self): """ Signing method. :return: signature """ _hash = SHA_2(self._sha, self._message).hash() rsa = RSA(self._rsa_key, None) self._rsa = rsa # sign signature = pkcs1_15.new(self._rsa.private_key).sign(_hash) # write signature to the file Helper.write_signature(['SHA-2', 'RSA'], [hex(int(self._sha)), hex(self._rsa.private_key.size_in_bits())], signature, Constants.signature_path) self._signature = signature
def test(): rsa = RSA() rsa.e = 3 rsa.d = 2011 rsa.n = 3127 message = "hello" print("Test known values e={}, d={}, n={}".format(rsa.e, rsa.d, rsa.n)) print("Message to encrypt/decrypt: " + message) enc = rsa.encrypt(message) print("Encrypted message: " + enc) dec = rsa.decrypt(enc) print("Decrypted message: " + dec)
def authenticate(self, sock): data = sock.recv(4096) username = data.decode() print(username) f = open('Users.txt', 'rb') users = pickle.load(f) f.close() currUser = '' for user in users: if user.username == username: currUser = username break if currUser == '': sock.sendall('Username not in record'.encode()) return False sock.sendall('Username Received'.encode()) data = b'' payload_size = struct.calcsize("L") print("Expecting Password") while len(data) < payload_size: data += sock.recv(4096) packed_msg_size = data[:payload_size] data = data[payload_size:] msg_size = struct.unpack("L", packed_msg_size)[0] while len(data) < msg_size: data += sock.recv(4096) block_data = data[:msg_size] data = data[msg_size:] password = pickle.loads(block_data) rsa = RSA() password = rsa.getDecryption(password, prKey[0], prKey[1]) f = open('Users.txt', 'rb') users = pickle.load(f) f.close() for user in users: if user.username == username: currUser = user break hashedPT = hashlib.sha256(password.encode()).hexdigest() if not hashedPT == user.password: return False return True
def encrypt(self): if not self.isLoaded: content = ErrorDialog(load=self.cos, cancel=self.dismiss_popup) self._popup = Popup(title="File not Loaded!", content=content, size_hint=(0.9, 0.9)) self._popup.open() if self.loaded_file is FILETYPE.WAV: content = ErrorDialog(load=self.cos, cancel=self.dismiss_popup) self._popup = Popup(title="Only BMP files are supported!", content=content, size_hint=(0.9, 0.9)) self._popup.open() elif self.loaded_file is FILETYPE.BMP: file = open(self.h.filename, "rb") image = file.read() file.close() header = image[:54] data = image[54:84] enc = self.rsaModule.encrypt( np.transpose(np.fromstring(data, dtype=np.uint8))) dec = self.rsaModule.decrypt(enc) print(np.fromstring(data, dtype=np.uint8)[0:10]) print(dec[0:10]) print(len(dec)) print(len(data)) print([ord(c) for c in data[0:10]]) print(dec[0:10]) file = open("example2.bmp", "wb") for i in range(len(dec)): if dec[i] > 255: print('RSA error') self.moduleRSA = RSA() return d = [int(v) for v in dec] d2 = [chr(v) for v in d] print(d2) file.write(header.join(d2)) file.close() print("--------------------------------------")
def task(): CHANCE = 5 RRRSA = RSA(1024) print(f"My public key: {RRRSA.e}, {RRRSA.N}") for _ in range(10): try: print(MENU) choice = input("Your choice: ") if choice == "1": m = int(input("Your message: ")) c = RRRSA.encrypt(m) print(f"Your cipher: {c}") elif choice == "2": c = int(input("Your message: ")) d = int(input("Your decryption exponent: ")) m = RRRSA.decrypt(c, d) print(f"Your message: {m}") elif choice == "3": RRRSA.gen_ed(1024) print(f"My new public key: {RRRSA.e}, {RRRSA.N}") elif choice == "4": if CHANCE: CHANCE -= 1 flag = int.from_bytes(FLAG, 'big') encflag = RRRSA.encrypt(flag) print(f"encflag: {encflag}") else: print("Nope, only 5 chances to get encflag.") else: print("Bye!") exit(0) except Exception as e: print(e) print("Error!") exit(-1)
def setKey(self, message, new_bits): #generate the RSA ans IDs self.message = message self.bits = new_bits self.e_RSA = 65537 # this value is given self.demoRSA = RSA() self.demoRSA.RSA(self.bits, self.e_RSA) self.demoRSA.sigGeneration(self.message) self.updateRSAKeys() self.IDs = int(1780119054 * random.random()) #not necessary to generate self.serverID = 1780119054 #just give -> can change any numbers
def console_mode(): print 'Welcome to RSA!' p, q = _get_primes_from_user() if not p or not q: bit_len = _get_bit_len_from_user() else: bit_len = max(p, q).bit_length() keys = key_gen.get_RSA_keys(bit_len, p, q) rsa_instance = RSA(n=keys[0][1], public_key=keys[0][0], private_key=keys[1][0], key_size=bit_len) while True: msg = _get_msg_to_enc() if msg == 'exit': break try: enc = rsa_instance.encrypt(msg) print 'Enc msg is: {}'.format(enc) dec = rsa_instance.decrypt(enc) print 'Dec msg is: {}'.format(dec) except Exception as e: print e
def test2(): rsa = RSA() rsa.e = 3 rsa.d = 2011 rsa.n = 3127 message = "hello" print("Test known values e={}, d={}, n={}".format(rsa.e, rsa.d, rsa.n)) print("Message: " + message) enc = rsa.encrypt(message) print("Encrypted message: " + enc) dec = rsa.decrypt(enc) print("Decrypted message: " + dec) sig = "andres" print("Signature: " + sig) dec2 = rsa.decrypt(sig, True) print("Generated Signature: " + dec2) auth = rsa.encrypt(dec2, True) print("After Authentication: " + auth)
def command_line(): '''Command line wrapper for RSA.py.''' parser = argparse.ArgumentParser( description='Command line interface for RSA encryption') parser.add_argument('-n', '--new-keys', action='store_true', help='Whether or not new keys should be generated.') parser.add_argument('-m', '--message', action='store', type=str, help='Message to be encoded.') parser.add_argument('-f', '--file', action='store', type=str, help='File to be encoded.') parser.add_argument('-o', '--output-location', action='store', type=str, help='Output location for the encoded message file') parser.add_argument('-c', '--coded-message', action='store', type=str, help='Location of message to be decoded.') parser.add_argument('-k', '--key-files', action='store', type=str, help='Location of the key files') parser.add_argument('-s', '--store-keys', action='store', type=str, help='Desired file location for output of keys') arguments = parser.parse_args() rsa = RSA(arguments.store_keys, arguments.output_location) if arguments.message and arguments.file: print("You can't both encode a file and a message at the same time") exit(1) if arguments.new_keys: rsa.RSA_keygen() if not arguments.key_files: if arguments.message or arguments.file: arguments.key_files = 'public.b' else: arguments.key_files = 'private.b' if arguments.file: with open(arguments.file) as file: rsa.RSA_encode(file.read(), arguments.key_files) exit(0) if arguments.message: rsa.RSA_encode(arguments.message, arguments.key_files) exit(0) if arguments.coded_message: message = rsa.RSA_decode(arguments.coded_message, arguments.key_files) print(message)
import os import time from RSA import RSA from AES import AES from KDF import KDF from Certificate import Certificate from MedirTiempos import MedirTiempos llaves = {128: 3072, 192: 7680, 256: 15380} origen = RSA() receptor = RSA() tiempos = MedirTiempos() documentos = os.listdir('documentos') iv = os.urandom(16) for x in llaves: bits = int(x / 8) # Se genera llave k para AES k = KDF().getAKey(bits) # Se obtienen las llaves asimetricas ya generadas desde un archivo (por cuestiones de tiempo) receptor.getKeys('receptor_keys', llaves[x]) origen.getKeys('emitter_keys', llaves[x]) # Lado cifrado # Se genera un certificado para las llaves del origen
def initClient(self): self.RSA = RSA() self.autenticate() self.connectToServer() threading.Thread(target=self.listenMessages).start() threading.Thread(target=self.chat).start()
def _get_public_key_from_server(self): data = self.server.recv(10240) key = self._get_key(data) self.RSA = RSA(public_key=key[0], n=key[1])
def main(): rsa = RSA() UI = CMDInterface(rsa) UI.display_menu()