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 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 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 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)
class Bob: def __init__(self,y,keys): self.y = y self.rsa = RSA(keys) self.util = Utilities() def computation(self,c1,m1,p): m2 = list() for i in range(xr+1): if i ==0: m2.append(-1) continue m2.append(self.rsa.decrypt(c1+i)) self.m2 = m2 count = 1 random.seed(datetime.now()) while count != 0: count = 0 self.p =p # input("p ki toh") z= list(range(xr+1)) for i in range(1,xr+1): z[i] = self.m2[i] %self.p for i in range(1,xr+1): for j in range(1,xr+1): if(abs(z[i]-z[j]) < 2 and i!=j ): print(i , " ",j ) count += 1 input("enter to contuneue") break if count >0: break self.z = z for i in range(1,xr+1): if i>y: self.z[i] = self.z[i]+1 return (self.z,self.p) def getZ(self): return self.z def getResult(self, response): if response: print("Value of Alice is greater than Bob's") else: print("Bob's value is greater than Alice's")
class Server(object): def __init__(self, host='', port=8080): self.host = host self.port = port self.conn = None self.socket = self._init_socket() self.init_new_client() def _init_socket(self): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((self.host, self.port)) s.listen(1) return s def init_new_client(self): self._init_rsa() self.connect_client() def _init_rsa(self): rsa_keys = key_gen.get_RSA_keys(consts.DEFAULT_KEY_SIZE) self.public_keys = rsa_keys[0] self.rsa_instance = RSA(n=rsa_keys[1][1], private_key=rsa_keys[1][0]) def connect_client(self): conn, addr = self.socket.accept() print 'Connected by', addr self.conn = conn conn.send('{}'.format(self.public_keys)) def listen_to_client(self): enc_msg = self.conn.recv(10240) if not enc_msg: print 'User disconnected, waiting for a new one' self.conn.close() self.conn = None return None return int(enc_msg) def decrypt_msg(self, cipher): return self.rsa_instance.decrypt(str(cipher)) def close(self): # First close connection to client, then close own connection self.conn.close() self.socket.close()
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)
class TestRSAOperations(unittest.TestCase): def setUp(self): self.p= DynamInt(10) self.q = DynamInt(10) #self.p.setData("821089628001493") #self.q.setData("1872967539195764008553239") self.rsa = RSA(0) self.rsa.createkeys(self.p, self.q) def test_encdec(self): ''' Test regular encoding and decoding of numbers ''' a = DynamInt() a.setData("25") rsa = RSA(0) rsa.p.setData("11") rsa.q.setData("3") rsa.e.setData("3") rsa.n.setData("33") rsa.phi.setData("20") rsa.d.setData("7") d = rsa.powmod(a,rsa.e,rsa.n) f = rsa.powmod(d,rsa.d,rsa.n) self.assertEqual(a.data, f.data) def test_disguise(self): strr = "iamaboy" rsa = RSA(0) num=rsa.disguise(strr) self.assertEqual("iamaboy", rsa.reveal(num)) def test_encryptionDecryption(self): # make sure we can encrypt and decrypt crypted = self.rsa.encrypt("iam") result = self.rsa.decrypt(crypted) temp='' for i in result: temp = temp+i self.assertEqual("iam", temp)
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 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
class DSA: def __init__(self, P, Q): self.P = P self.Q = Q self.encryptor = RSA(self.P, self.Q) self.e, self.d, self.n = self.encryptor.generate_keys() def get_hash(self, message): hash_input = bytes(message, "utf-8") hash_digest = SHA1HASH(hash_input).final_hash() return hash_digest def sign_document(self, input_file): with open(input_file) as f: message = f.read() hash_digest = self.get_hash(message) print("Public keys are e:{}, n:{}".format(self.e, self.n)) print("Private keys are d:{}, n:{}".format(self.d, self.n)) ciphertext = self.encryptor.encrypt(hash_digest) return ciphertext def verify_document(self, input_file, ciphertext): with open(input_file) as f: message = f.read() hash_digest = self.get_hash(message) plaintext = self.encryptor.decrypt(ciphertext) if plaintext == hash_digest: return False else: return True
from RSA import RSA type1 = RSA(1000) '''type1.print_vars() type1.get_public() type1.get_private()''' x = type1.encrypt(5) y = type1.decrypt(x) print('\nencrypted is: ', x, "\ndecrypted is: ", y)
from RSA import RSA as rsa program = rsa.RSAProgram() message = rsa.encrypt(program.modulus, program.encrypt) print(message) raw_input('press enter when ready to decrypt').lower() print(rsa.decrypt(message, program.decrypt, program.modulus))
''' RSA_OOP_test @author: Sollazzo Nicholas @date: March 20th 2017 @version: 1.0 @status: GREEN ''' from RSA import RSA rsa = RSA() print(rsa.dict()) #en = rsa.encrypt(input('>')) en = rsa.encrypt('das') print('encrypted:', en) print('decrypted:', rsa.decrypt(en))
class Root(FloatLayout): loadfile = ObjectProperty(None) text_input = ObjectProperty(None) text_input2 = ObjectProperty(None) text_input3 = ObjectProperty(None) def __init__(self): super(self.__class__, self).__init__() self.isLoaded = False self.loaded_file = FILETYPE.UNKNOWN self.h = '' self.rsaModule = RSA() def dismiss_popup(self): self._popup.dismiss() def show_load(self): content = LoadDialog(load=self.load, cancel=self.dismiss_popup) self._popup = Popup(title="Load file", content=content, size_hint=(0.9, 0.9)) self._popup.open() def load(self, path, filename): if filename[0][-4:] == ".wav": self.h = HeaderBuilderWAV() self.loaded_file = FILETYPE.WAV elif filename[0][-4:] == ".bmp": self.h = HeaderBuilderBMP() self.loaded_file = FILETYPE.BMP else: raise ValueError('Not known extension of file') self.h.readHeader(os.path.join(path, filename[0])) self.text_input.text = str(self.h.header) self.dismiss_popup() self.isLoaded = True def cos(self): self.dismiss_popup() def display_wav_fft(self, samples, sample_rate, num_channels, fignum): #time vector n = len(samples) k = np.arange(n) T = float(n) / sample_rate freq = k / T freq = freq[range(n / 2)] fig, ax = plt.subplots(num_channels, 1) for i in range(0, num_channels): plt.figure(fignum) #calculate fft and normalize results if num_channels is 1: y = np.fft.fft(samples) / n y = y[range(n / 2)] plt.plot(freq, abs(y)) plt.title('Channel {} FFT'.format(i + 1)) plt.xlabel('Freq (Hz)') else: y = np.fft.fft(samples[:, i]) / n y = y[range(n / 2)] ax[i].plot(freq, abs(y)) ax[i].set_title('Channel {} FFT'.format(i + 1)) ax[i].set_xlabel('Freq (Hz)') def display_bmp_fft(self, samples): plt.figure(1) fft = fftpack.fft2(samples) plt.imshow(np.abs(np.fft.fftshift(fft)), interpolation='nearest') plt.show() def fourier_transform(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() #return Button(text='Hello World') else: if self.loaded_file is FILETYPE.WAV: sample_rate = self.h.header.get_property("SampleRate") num_channels = self.h.header.get_property("NumChannels") self.display_wav_fft(self.h.data[0:1000], sample_rate, num_channels, 1) plt.show() elif self.loaded_file is FILETYPE.BMP: self.display_bmp_fft(self.h.data) #rsaModule = RSA() #enc = rsaModule.encrypt(self.h.data) #dec = rsaModule.decrypt(enc) #if (self.h.data==dec).all: # print "good" #else: # print "bad" 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 decrypt(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:] print(np.fromstring(data, dtype=np.uint8)[0:10])
from values import * from RSA import RSA if __name__ == "__main__": rsa = RSA(p, q, a) rsa.decrypt(rsa.encrypt(message))
def run_RSA(s): r = RSA(16) c = r.encrypt(s) m = r.decrypt(c) assert s.hex() == m.hex()
class ClientThread(Thread): def __init__(self, HOST, PORT, NICK): super(ClientThread, self).__init__() self.ONLINE_LIST = [] self.nick = NICK self.cbox = None self.RSA_Scheme = RSA() self.BREA_Scheme = BREA() self.receiver = "broadcast" self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sep = chr(7) self.broadcast = 1 self.HOST = socket.gethostbyname(str(HOST)) self.PORT = PORT self.isconnected = 1 self.root = 0 self.online_list = [] try: self.sock.connect((self.HOST, self.PORT)) except: self.isconnected = 0 def reconnect(self): try: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((self.HOST, self.PORT)) self.sock.send('2' + self.sep + self.nick + self.sep + self.RSA_Scheme.getPublicKey()) data = self.sock.recv(4096) self.online_list = data.split(self.sep) if self.online_list[0] == '2': for i in range(1, len(self.online_list), 2): self.cbox.online.addItem(self.online_list[i]) self.ONLINE_LIST.append((self.online_list[i], self.online_list[i+1])) except: pass def run(self): while True: try: msg = self.sock.recv(4096) except: self.ONLINE_LIST = [] self.online_list = [] self.cbox.online.clear() self.reconnect() continue ins = msg.split(self.sep) if ins[0] == '1': if self.cbox.connected.text() == "Connected to " + ins[1]: self.cbox.connected.setText("Connected to <No User>") for i in range(self.cbox.online.count()): if self.cbox.online.item(i).text() == ins[1]: self.cbox.online.takeItem(i) break for i in self.ONLINE_LIST: if i[0] == ins[1]: self.ONLINE_LIST.remove(i) break elif ins[0] == '2': for i in range(1, len(ins), 2): self.cbox.online.addItem(ins[i]) self.ONLINE_LIST.append((ins[i], ins[i+1])) elif ins[0] == '3': if ins[2] == self.nick or self.root == 1: key = ins[4] msg = self.BREA_Scheme.decrypt(ins[3], self.RSA_Scheme.decrypt(key)) self.cbox.win.append("[" + ins[1] + "] " + msg) elif ins[0] == "4": self.cbox.win.append("[" + ins[1] + "] " + ins[2]) def nickValidate(self, txt): sent = "2" + self.sep + txt + self.sep + self.RSA_Scheme.getPublicKey() self.sock.send(sent) ret = self.sock.recv(4096) ret = ret.split(self.sep) self.online_list = ret return ret
# Lado decifrado # Se obtiene la llave pública para verificar firmas receptor.setEntityKey(origen.getPublicKey()) ########## Tiempo de verificación de certificado ############### # Se verifica la autenticidad de la llave con el certificado tiempos.medir(f'verificacioncertificado_{llaves[x]}') esCorrecto = cer.validateCertificate(certificado, receptor.getEntityKey()) tiempos.medir(f'verificacioncertificado_{llaves[x]}') ################################################################ if esCorrecto: ########## Tiempo de descifrado ############### # Se descifra la llave enviada por el origen tiempos.medir(f'descifradollave_{x}') key = receptor.decrypt(cypherKey) tiempos.medir(f'descifradollave_{x}') ############################################### # Se decifran los documentos for documento in documentos: # Se instancia el cifrador con la llave recibida aesr = AES(key, iv) # Se lee el archivo nombre = documento.split('.') f = open(f'documcifrados/{nombre[0]}', 'rb') contenido = f.read() f.close() # Se separa la firma del contenido contenido = contenido.split(b'firma')
from RSA import RSA if __name__ == '__main__': rsa = RSA() while True: inp = input("uzenet: ") choice = 999 while not int(choice) in range(1, 2 + 1): print("1) visszafejtes") print("2) titkositas") choice = input() if int(choice) == 1: print(rsa.decrypt(int(inp))) else: print(rsa.encrypt(inp))