def test_wiring_characters_are_unique(self): self.assertTrue( isinstance(Encryptor(wiring='ABCDEFGHIJKLMNOPQRSTUVWXYZ'), Encryptor)) with self.assertRaises(ValueError): Encryptor(wiring='ABCDEFGHIJKLMABCDEFGHIJKLMN')
def test_wiring_is_alphabetic(self): self.assertTrue( isinstance(Encryptor(wiring='abcdefghijklmnopqrstuvwxyz'), Encryptor)) with self.assertRaises(ValueError): Encryptor(wiring='ABCDEFGHIJKLMNOPQRSTUVWX.!')
def test_initial_position_is_valid(self): self.assertTrue(isinstance(Encryptor(initial_position=7), Encryptor)) with self.assertRaises(ValueError): Encryptor(initial_position=-1) with self.assertRaises(TypeError): Encryptor(initial_position='a pencil') with self.assertRaises(ValueError): Encryptor(initial_position=27)
def new_user(user, passwd): #function to create and insert new user in the database if len(user) == 0 or len(passwd) == 0: return 0 try: passwd = Encryptor().encrypt(passwd) cursor.execute( "INSERT INTO users (username,password) VALUES ('%s','%s')" % (user, passwd)) cursor.execute( "CREATE TABLE %s (name varchar(100) not null unique,url varchar(5000) not null,username varchar(100) not null,password varchar(100) not null)" % (user)) url = 'https://accounts.google.com/signin/v2/identifier?service=mail&passive=true&rm=false&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&ss=1&scc=1<mpl=default<mplcache=2&emr=1&osid=1&flowName=GlifWebSignIn&flowEntry=ServiceLogin' cursor.execute( "INSERT INTO %s VALUES ('Gmail','%s','*****@*****.**','InsertPassword')" % (user, url)) url = 'https://www.facebook.com/login.php' cursor.execute( "INSERT INTO %s VALUES ('Facebook','%s','*****@*****.**','InsertPassword')" % (user, url)) url = 'https://www.instagram.com/accounts/login/' cursor.execute( "INSERT INTO %s VALUES ('Instagram','%s','Coolusername','InsertPassword')" % (user, url)) url = 'https://www.linkedin.com/uas/login-submit' cursor.execute( "INSERT INTO %s VALUES ('Linkedin','%s','Coolusername','InsertPassword')" % (user, url)) sql_conn.commit() return 1 except: return 0
def __init__(self, public_key_server): self.broker_comm = BrokerCommunicator() self.public_key_server = public_key_server self.db_list = None self.mixnode_list = None self.ip = getPublicIp() self.encryptor = Encryptor(getGlobalSphinxParams().group) self.surbDict = {}
class encryptorTest(unittest.TestCase): __encryptor = Encryptor() def setUp(self): return super().setUp() def testhash(self): self.assertEqual(self.__encryptor.hash('Gree56'), 'd730f134b4dbd3878ce97dc55ee57067a543438fd1ef4702b904097b528dcb9baf3b22a4271647e8050198dfe27eef466248d20b85c0f6b9e4cb14845c3c0405')
def encrypt_words(self, words): ''' Requirement: I want to encrypt each word in the sentence. ''' retval = list() for word in words: retval.append(Encryptor(word)) return retval
def encrypt_file(path, public_key, key_length): with open(path, 'rb') as file: file_bytes = file.read() file_bytes = Encryptor(key_length, public_key).encrypt(file_bytes) file.close() file = open(path, 'wb') file.write(file_bytes)
def edit_entry(table, name, url, username, password, oldname): try: password = Encryptor().encrypt(password) cursor.execute( 'UPDATE %s SET name="%s", url="%s",username="******",password="******" WHERE name="%s"' % (table, name, url, username, password, oldname)) sql_conn.commit() cursor.execute('SELECT * FROM %s' % (table)) return cursor.fetchall() except: return 0
def new_entry(table, name, url, username, password): try: password = Encryptor().encrypt(password) print password cursor.execute("INSERT INTO %s VALUES ('%s','%s','%s','%s')" % (table, name, url, username, password)) sql_conn.commit() cursor.execute("SELECT * FROM %s" % (table)) return cursor.fetchall() except: return 0
def test_reverse_encrypt_character(self): e = Encryptor(wiring=Encryptor.ALPHABET, initial_position=1) self.assertEqual(e.reverse_encrypt_character('B'), 'A') self.assertEqual(e.reverse_encrypt_character('R'), 'Q') with self.assertRaises(TypeError): e.reverse_encrypt_character(-3) with self.assertRaises(ValueError): e.reverse_encrypt_character('flamingo')
def test_encrypt_character(self): e = Encryptor(wiring=Encryptor.ALPHABET, initial_position=1) self.assertEqual(e.encrypt_character('A'), 'B') self.assertEqual(e.encrypt_character('Q'), 'R') with self.assertRaises(TypeError): e.encrypt_character(-3) with self.assertRaises(ValueError): e.encrypt_character('an aardvark')
def generateCiphertext(self): encryptor = Encryptor() key = encryptor.secretGenerator() carId = getpass.getpass('CarID: ') deviceID = getpass.getpass('DeviceID: ') carIdEncrypted = encryptor.encryptMsg(carId, key) deviceIDEncrypted = encryptor.encryptMsg(deviceID, key) return (carIdEncrypted, deviceIDEncrypted)
def verify_password(username, password): encryptor = Encryptor() username = encryptor.desencryptMsg(username) password = encryptor.desencryptMsg(password) res = requests.get("http://34.82.167.68/car/verify?licensePlate=" + username + "&sensorId=" + password, timeout=3) if res.text == "true": return True else: return False
def __init__(self, broker_config): self.private_key = None self.public_key = None self.ip = None self.params = getGlobalSphinxParams() self.network_sender = NetworkSender() self.broker_config = broker_config self.encryptor = Encryptor(self.params.group) self.mixnodes_list = None self.broker_comm = BrokerCommunicator() self.records = {} self.loadRecords() self.decoder = BinaryEncoderDecoder()
def __init__(self, broker_config, pool_size=3): self.private_key = None self.public_key = None self.ip = None self.params = getGlobalSphinxParams() self.network_sender = NetworkSender() self.broker_config = broker_config self.encryptor = Encryptor(self.params.group) self.db_list = None self.broker_comm = BrokerCommunicator() self.client_cache = {} self.mix_pool = MixPool(pool_size) self.client_backlog = set()
def encrypt_button(self, passwd, filename): response = False if (filename == ""): messagebox.showerror("Error", "Please select a file!") elif(passwd == ""): messagebox.showerror("Error", "Please enter a password!") else: response = messagebox.askyesno("Enrypt", "Are you sure?") if(response): self.key = passwd.encode('UTF-8') enc = Encryptor(self.key) enc.encrypt_file(filename) messagebox.showinfo("Succes", "Encryption successful") pass
def distil_sentence(self, words, step_index): ''' Requirement: Then I want to encrypt again by combining pairs of words. I want to keep doing this until there is a single encrypted string that represents the sentence. ''' result = list() # loops over pairs: for index in range(1, len(words), 2): string_to_encrypt = str(words[index - 1]) + ' ' + str(words[index]) result.append(Encryptor(string_to_encrypt)) # is the list count odd? then encrypt the guy at the end: if len(words) % 2 == 1: result.append(Encryptor(str(words[-1]))) # negative array indexes take from the end of the list. print(f"Encrypted pass {step_index}: {' '.join(str(w) for w in result)}") if len(result) > 1: return self.distil_sentence(result, step_index + 1) # return the only word left: return str(result[0])
def test_encryptor_encrypt_decrypt(): params = SphinxParams() group = params.group encryptor = Encryptor(group) msg = hexlify(str(11).encode()) session_name = os.urandom(16) ## Alice pk, sk = encryptor.keyGenerate('test') ## Bob public_key_expon, iv, ciphertext, tag = encryptor.encrypt_aes_gcm(msg, pk[2], session_name) ## Alice msg_decrypted = encryptor.decrypt_aes_gcm( (public_key_expon, iv, ciphertext, tag), sk.x) assert(msg_decrypted == msg)
def log_in(user, passwd): #function to verify and login the user in the database cursor.execute('SELECT * FROM users WHERE username="******"' % (user)) detvar = cursor.fetchone() print detvar if (detvar == None or len(detvar[0]) == 0): return 0 else: print detvar[1] if Encryptor().decrypt(str(detvar[1])) == passwd: cursor.execute("SELECT * FROM %s" % (user)) return cursor.fetchall() else: return 0
class Server_Connector: encryptor = Encryptor() iocontroller = IO_controller() def __init__(self, IP_address, port): print('Creating socket') self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.IP_address = IP_address self.port = port def run(self): self.s.connect((self.IP_address, self.port)) print('Succesfully connected to: ', self.IP_address) # Send a 1 to the server to let it know that you're a robot self.send('1') message = self.s.receive(1024) json_message = {'ready': True} self.send(json_message) while True: message = self.receive() if (message['type'] == 'route'): directions = message['routes'] for directionlist in directions: for direction in directionlist: print('Next direction: ' + direction) while (self.iocontroller.detect_node() == "line"): pass if (self.iocontroller.detect_node() == "node"): # TODO draai naar dirction print("Node detected") #self.iocontroller.control_motors(directions) def send(self, message): jsonmessage = json.dumps(message) encryptedmessage = self.encryptor.encrypt(jsonmessage) self.s.send(encryptedmessage) def receive(self): receivedmessage = self.s.recv(1024) receivedmessage = self.encryptor.decrypt(receivedmessage) return json.loads(receivedmessage)
def fTestEnc(): print("fTestEnc") e = Encryptor() # Check fGenDict d = e.fGenDict() # check if every char in dict success = True for c in Encryptor.chars: if not c in d and success: print("fGenDict FAILED!") success = False if success: print("fGenDict Success!") # Check fReverseDict success = True rd = e.fReverseDict(d) for k, v in rd.items(): if not d[v] == k and success: print("fReverseDict FAILED!") if success: print("fReverseDict Success!") # check key encryption msg = "quick brown fox jumped over fence!><P@*ASND *!@ DHA" # fGenKeys, nothing to check # keys = e.fGenKeys(len(msg)//2, len(msg)//6 + 1) keys = [1, 2, 3] # fEncryptKeys and fDecryptKeys mk = e.fEncryptKeys(msg, e.default, keys) if mk == msg: print("fEncryptKeys FAILED!") else: print("fEncryptKeys Success!") mk = e.fDecryptKeys(mk, e.default, keys) if mk != msg: print("fDecryptKeys FAILED!") print(mk, msg) else: print("fDecryptKeys Success!") # fEncryptDict and with reversed dict success = True mk = e.fEncryptDict(msg, d) if mk == msg: print("fEncryptDict FAILED!") else: print("fEncryptDict Success!") mk = e.fEncryptDict(mk, rd) if mk != msg: print("fEncryptDict in reverse FAILED!") print(msg, mk) else: print("fEncryptDict in reverse Success!") # fGenFuncs fEnc, fDec = e.fGenFuncs(20) mk = fEnc(msg) if mk == msg: print("fGenFuncs fEnc FAILED!") else: print("fGenFuncs fEnc Success!") mk = fDec(mk) if msg != mk: print("fGenFuncs fDec FAILED") else: print("fGenFuncs fDec Success!")
class Gui: flag = 1 window = Tk() window.geometry("430x450") window.resizable(0, 0) window.title("Installation Wizard") e = Encryptor() # def btn_click(self, item): # global expression # expression = expression + str(item) # input_text.set(expression) # # def btn_clear(self): # global expression # expression = "" # input_text.set("") # # def btn_equal(self): # global expression # result = str(eval(expression)) # input_text.set(result) # expression = "" def execute(self, flag): if path.exists("./network/encryptor/network.json"): self.labelText.set( "Application is already installed in your system\nClose this window and launch the application" ) else: global expression expression = "" self.labelText.set( "Installing the encryptor\nSee terminal for details") self.e.main() self.labelText.set("Installation Finished") self.flag = 0 def destroy_session(self, window): window.destroy() expression = "" input_text = StringVar() labelText = StringVar() input_frame = Frame(window, width=312, height=50, bd=0, highlightbackground="black", highlightcolor="black", highlightthickness=1) input_frame.pack(side=TOP) input_field = Entry(input_frame, font=('arial', 18, 'bold'), textvariable=input_text, width=50, bg="#eee", bd=0, justify=RIGHT) input_field.grid(row=0, column=0) input_field.pack(ipady=10) btns_frame = Frame(window, width=312, height=272.5) btns_frame.pack(side=TOP) btns_frame2 = Frame(window, width=312, height=72.5, bg="grey") btns_frame2.pack(side=BOTTOM) label = Label(btns_frame, text="Neural Encryptor", fg="Red", width=55, height=3, bd=0, bg="#cfa").grid( row=0, column=0, columnspan=2, ) install = Button(btns_frame, text="Install", fg="black", font=('Times new roman', 12, 'bold'), width=24, height=3, bd=2, bg="#fff", cursor="hand2", command=lambda: Gui().execute(Gui().flag)).grid( row=1, column=0, ) destroy = Button(btns_frame, text="Exit", fg="black", font=('Times new roman', 12, 'bold'), width=24, height=3, bd=2, bg="#fff", cursor="hand2", command=lambda: Gui().destroy_session(Gui().window)).grid( row=1, column=1, ) message = Label( btns_frame, textvariable=labelText, fg="Black", font=('Times new roman', 12, 'bold'), width=55, height=12, bd=0, ).grid( row=2, column=0, columnspan=2, pady=5, ) s = "Developed by : Saketh G" label2 = Label(btns_frame2, text=s, fg="Black", width=55, height=1, bd=0, bg="#cfa").grid(row=3, column=0, columnspan=2)
class Functionalities: additional = AdditionalFunctions() encryptor = Encryptor() def checkEfficiency(self): k = list() with open('./network/encryptor/network.json') as data_file: network = json.load(data_file) n = self.encryptor.getAsciiData() dataset = list() for i in n: i = list(i) i = list(map(int, i)) i.append(0) dataset.append(i) for i in range(100): k.append(self.encryptor.predict(network, dataset[i], 0)) k[i].append(dataset[i][:-1]) c = list() for i in k: s = "" i = list(map(str, i)) c.append(s.join(i)) s = "Network is {}% efficient".format(len(list(dict.fromkeys(c)))) return s def beginEncryption(self, file_path): with open('./network/encryptor/network.json') as data_file: network = json.load(data_file) data = list() f = open(file_path, "r") line = f.readline() while line != '': data.append(line) line = f.readline() bit_data = list() for i in data: bit_data.append(self.additional.text_to_bits(i)) flag = 1 for i in range(len(bit_data)): if ((len(bit_data[i])) % 8) != 0: print("data corrupted") flag = 0 break if flag: input_data = list() for i in bit_data: l = len(i) k = int(l / 8) c = 0 for j in range(k): s = i[c:c + 8] input_data.append(s) c += 8 c = 0 for i in bit_data: l = len(i) c += int(l / 8) if c == len(input_data): print("data input is ready") bit_data = list() for i in input_data: a = list(i) b = list(i) a = list(map(int, a)) b = list(map(int, b)) a.append(b) bit_data.append(a) input_data = list() for i in bit_data: input_data.append(self.encryptor.predict(network, i, 0)) bit_data = list() for i in input_data: s = "" i = list(map(str, i)) bit_data.append(s.join(i)) s = "" for i in bit_data: s += i code = base64.b64encode(zlib.compress(s.encode('utf-8'), 9)) code = code.decode('utf-8') now = datetime.now() d1 = "./data/encrypted/" + now.strftime("%Y_%m_%d_%H%M%S") + ".txt" f = open(d1, 'w') f.write(code) f.close() s = "Encrypting the file \n{} \nis successfully completed".format( file_path.split("/")[-1]) s += "\nEncrypted file stored at: \n{}".format(d1) return s def beginDecryption(self, file_path): with open('./network/decryptor/network_bit_2.json') as data_file: network2 = json.load(data_file) with open('./network/decryptor/network_bit_3.json') as data_file: network3 = json.load(data_file) with open('./network/decryptor/network_bit_4.json') as data_file: network4 = json.load(data_file) with open('./network/decryptor/network_bit_5.json') as data_file: network5 = json.load(data_file) with open('./network/decryptor/network_bit_6.json') as data_file: network6 = json.load(data_file) with open('./network/decryptor/network_bit_7.json') as data_file: network7 = json.load(data_file) with open('./network/decryptor/network_bit_8.json') as data_file: network8 = json.load(data_file) print("Enter path to encrypted file") file = open(file_path, 'r') text = file.read() file.close() decoded_txt = zlib.decompress(base64.b64decode(text)) output = decoded_txt.decode() if len(output) % 8 != 0: print("corrupted data") else: c = 0 l = len(output) k = int(l / 8) s = "" for i in range(k): word = list(output[c:c + 8]) word = list(map(int, output[c:c + 8])) word.append(0) s += "0" s += self.encryptor.predict(network2, word, 2) s += self.encryptor.predict(network3, word, 3) s += self.encryptor.predict(network4, word, 2) s += self.encryptor.predict(network5, word, 2) s += self.encryptor.predict(network6, word, 2) s += self.encryptor.predict(network7, word, 2) s += self.encryptor.predict(network8, word, 2) c += 8 c = 0 l = len(output) k = int(l / 8) o = "" for i in range(k): u = self.additional.text_from_bits(s[c:c + 8]) o += u c += 8 now = datetime.now() d1 = "./data/decrypted/" + now.strftime("%Y_%m_%d_%H%M%S") + ".txt" f = open(d1, 'w') f.write(o) f.close() s = "Decrypting the file \n{} \nis successfully completed".format( file_path.split("/")[-1]) s += "\nDecrypted file stored at \n{}".format(d1) return s
class Decryptor: encryptor = Encryptor() def main(self): #creating dataset for the system network = list() dataset = self.getDataset() for i in range(7): print("Training Decryptor for bit {} initiated".format(i + 2)) if i == 0 or i == 1 or i == 2: layers = [8, 9, 7, 1] elif i == 3 or i == 4 or i == 6: layers = [8, 10, 9, 1] else: layers = [8, 9, 3, 1] l_rate = 1.0 epochs = 10000 network = self.encryptor.createEncryptor(dataset[i], layers, l_rate, epochs) name = './network/decryptor/network_bit_' + str(i + 2) + '.json' with io.open(name, 'w', encoding='utf8') as outfile: str_ = json.dumps(network, indent=4, sort_keys=True, separators=(',', ': '), ensure_ascii=False) outfile.write(to_unicode(str_)) self.checkEfficiency(network, dataset[i]) def getDataset(self): final_temp = list() with open('./data/languageDecryptor.json') as data_file: temp1 = json.load(data_file) with open('./data/languageDecryptor.json') as data_file: temp2 = json.load(data_file) with open('./data/languageDecryptor.json') as data_file: temp3 = json.load(data_file) with open('./data/languageDecryptor.json') as data_file: temp4 = json.load(data_file) with open('./data/languageDecryptor.json') as data_file: temp5 = json.load(data_file) with open('./data/languageDecryptor.json') as data_file: temp6 = json.load(data_file) with open('./data/languageDecryptor.json') as data_file: temp7 = json.load(data_file) for i in range(100): temp1[i][-1] = temp1[i][-1][1:2] temp2[i][-1] = temp2[i][-1][2:3] temp3[i][-1] = temp3[i][-1][3:4] temp4[i][-1] = temp4[i][-1][4:5] temp5[i][-1] = temp5[i][-1][5:6] temp6[i][-1] = temp6[i][-1][6:7] temp7[i][-1] = temp7[i][-1][7:] print(temp1) final_temp.append(temp1) final_temp.append(temp2) final_temp.append(temp3) final_temp.append(temp4) final_temp.append(temp5) final_temp.append(temp6) final_temp.append(temp7) return final_temp def checkEfficiency(self, network, dataset): c = 0 for j in dataset: k = self.encryptor.predict(network, j, 0) s = "" k = list(map(str, k)) k = s.join(k) p = j[-1] s = "" p = list(map(str, p)) p = s.join(p) if (k != p): c += 1 print("Efficiency of this decryptor is " + str(c) + " %")
if(choice == '1'): inputEmail = input("Enter email address: ") inputPassword = input("Enter password: "******"Logging in user: "******"Enter email address: ") inputPassword = input("Enter password: "******"Input options: \n\t1: Send message \n\t2: Check messages \n\t3: Logout\n") option = input("Input choice: ") if(option == '1'): #send message recipient = input("Enter recipient email: ") msg = input("Enter message:\t") encryptedMsg = myEncryptor.encrypt(msg) #encrypt message before sending myClient.postMsg(chatURL, recipient, encryptedMsg) #send encrypted message elif(option == '2'): #check messages responseData = myClient.getMsg(chatURL) #send get request
from encryptor import Encryptor from disks import Disks from constants import SHIFT if __name__ == '__main__': text = 'Some encrypted tex' discs = Disks().discs out = Encryptor().jefferson_encryption(text, discs, SHIFT, reverse=False) print(out)
def __init__(self): self.carriageReturn = chr(13) self._data = Encryptor.getData(Encryptor())
def encrypt_button(self, passwd): response = messagebox.askyesno("Enrypt", "Are you sure?") key = passwd.encode('UTF-8') enc = Encryptor(key) enc.encrypt_file(self.filename) pass
from encryptor import Encryptor encryptor = Encryptor() encrypted = '' #string = input('Enter string to be encrypted: ') string = encryptor.loadFile('text.txt') chars = encryptor.getChars() newChars = encryptor.encrypt(string) for i in range(len(newChars)): print(newChars[i]) for i in range(len(newChars)): encrypted += newChars[i] decrypted = encryptor.decrypt(encrypted) for i in range(len(newChars)): print(decrypted[i])