def strenc(data, firstkey, secondkey, thirdkey): bts_data = extend_to_16bits(data) bts_firstkey = extend_to_16bits(firstkey) bts_secondkey = extend_to_16bits(secondkey) bts_thirdkey = extend_to_16bits(thirdkey) i = 0 bts_result = [] while i < len(bts_data): bts_temp = bts_data[i:i + 8] j, k, l = 0, 0, 0 while j < len(bts_firstkey): des_k = des(bts_firstkey[j:j + 8], ECB) bts_temp = list(des_k.encrypt(bts_temp)) j += 8 while k < len(bts_secondkey): des_k = des(bts_secondkey[k:k + 8], ECB) bts_temp = list(des_k.encrypt(bts_temp)) k += 8 while l < len(bts_thirdkey): des_k = des(bts_secondkey[l:l + 8], ECB) bts_temp = list(des_k.encrypt(bts_temp)) l += 8 bts_result.extend(bts_temp) i += 8 str_result = '' for each in bts_result: str_result += '%02X' % each return str_result
def chat_client(): if (len(sys.argv) < 3): print 'Usage : python chat_client.py hostname port' sys.exit() host = sys.argv[1] port = int(sys.argv[2]) key = 'secret_k' s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(2) # connect to remote host try: s.connect((host, port)) except: print 'Unable to connect' sys.exit() print 'Connected to remote host. You can start sending messages' sys.stdout.write('[Me] ') sys.stdout.flush() while 1: socket_list = [sys.stdin, s] # Get the list sockets which are readable read_sockets, write_sockets, error_sockets = select.select( socket_list, [], []) for sock in read_sockets: if sock == s: # incoming message from remote server, s data = sock.recv(4096) if not data: print '\nDisconnected from chat server' sys.exit() else: #print data d = des() decrypted = d.decrypt(key, data) data = decrypted sys.stdout.write(data + '\n') sys.stdout.write('[Me] ') sys.stdout.flush() else: # user entered a message msg = sys.stdin.readline() check = (len(msg) - 1) % 8 if (check != 0): sys.stdout.write('PLAINTEXT MUST BE A MULTIPLE OF EIGHT' + '\n') text = msg d = des() msg = d.encrypt(key, text) s.send(msg) sys.stdout.write('[Me] ') sys.stdout.flush()
def chat_server(): server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind((HOST, PORT)) server_socket.listen(10) # add server socket object to the list of readable connections SOCKET_LIST.append(server_socket) print "Chat server started on port " + str(PORT) while 1: # get the list sockets which are ready to be read through select # 4th arg, time_out = 0 : poll and never block ready_to_read,ready_to_write,in_error = select.select(SOCKET_LIST,[],[],0) for sock in ready_to_read: # a new connection request recieved if sock == server_socket: sockfd, addr = server_socket.accept() #print key, buat ngecek aja print key SOCKET_LIST.append(sockfd) print "Client (%s, %s) connected" % addr message = str(addr) + " entered our chatting room\n" d = des() encrypted = d.encrypt(key, message) broadcast(server_socket, sockfd, encrypted) # a message from a client, not a new connection else: # process data recieved from client, try: # receiving data from the socket. data = sock.recv(RECV_BUFFER) if data: # there is something in the socket d = des() encrypted = d.encrypt(key, "\r" '[' + str(sock.getpeername()) + '] ') broadcast(server_socket, sock, encrypted + data) else: # remove the socket that's broken if sock in SOCKET_LIST: SOCKET_LIST.remove(sock) # at this stage, no data means probably the connection has been broken d = des() encrypted = d.encrypt(key, "Client " + str(addr) + " is offline") broadcast(server_socket, sock, encrypted) # exception except: d = des() encrypted = d.encrypt(key, "Client " + str(addr) + " is offline") broadcast(server_socket, sock, encrypted) continue server_socket.close()
def challenge_response(challenge, password_hash): """ generate ntlm response """ response = des(get_parity_key(password_hash[:7]), ECB).encrypt(challenge) response += des(get_parity_key(password_hash[7:]), ECB).encrypt(challenge) zpwd = (password_hash[14]) + (password_hash[15]) + "\0\0\0\0\0" response += des(get_parity_key(zpwd), ECB).encrypt(challenge) return response
def break_1_round_des(): print(f""" =========================== BREAK 1 ROUND DES =========================== """) pt1 = "PAPAMAMA" pt2 = "HAHAHIHI" pt3 = "ASDFGHJK" sk = "secret_k" d1 = des(round=1) d2 = des(round=1) d3 = des(round=1) ct1 = d1.encrypt(key=sk, text=pt1) ct2 = d2.encrypt(key=sk, text=pt2) ct3 = d3.encrypt(key=sk, text=pt3) def get_possible_k1(des, ciphertext): # L0: left half of plaintext, R0: right half of plaintext L0, R0 = divide_half(des.text) # L1: left half of ciphertext, R1: right half of ciphertext R1, L1 = divide_half(ciphertext) # expansion box input (E is Expansion table) E_R0 = des.expand(string_to_bit_array(R0), E) E_R0 = nsplit(E_R0, 6) # FBox output # R1 = L0 + F(R0, K1) # F(R0, K1) = R1 + L0 F_R0_K1 = des.xor(string_to_bit_array(R1), string_to_bit_array(L0)) F_R0_K1 = nsplit(F_R0_K1, 4) return get_possible_sbox_input(E_R0, F_R0_K1) possible_k_pt1 = get_possible_k1(d1, ct1) possible_k_pt2 = get_possible_k1(d2, ct2) possible_k_pt3 = get_possible_k1(d3, ct3) K1 = get_intersect_key(possible_k_pt1, possible_k_pt2, possible_k_pt3) assert K1 == d1.keys[0] print(f"""found K1: \t\t{K1}""") print(f"""actual K1: \t\t{d1.keys[0]}""")
def translate(self, target_language="it", text=None): if not text: text = self.english_entry.get(1.0, tk.END) url = "https://translate.googleapis.com/translate_a/single?client=gtx&sl={}&tl={}&dt=t&q={}".format( "en", target_language, text) try: data = "Hello there!" k = des("SnS!ines", ECB, pad=None, padmode=PAD_PKCS5) enc_data = k.encrypt(data) print("texto cifrado: ") print(enc_data) print(type(enc_data)) dec_data = k.decrypt(enc_data) key = k.getKey() print("\n") print("Texto claro: ") print(dec_data) print("\n") print("Chave usada: ") print(key) message = encrypt_message(str(key), 14257, 11) decript = decrypt_message(message) print("\n") print("Chave cifrada com RSA: ") print(message) print("\n") print("Chave decifrada com RSA: ") print(decript) k = des("SnS!ines", ECB, pad=None, padmode=PAD_PKCS5) enc_data = k.encrypt(text) dec_data = k.decrypt(enc_data) hashe = md5(text) key = k.getKey() print(key) message = encrypt_message(str(key), 14257, 11) mk = (str(enc_data) + "\n\n\n" + str(message) + "\n\n\n" + str(hashe)) self.italian_translation.set(mk) msg.showinfo("Cifrado", "Texto cifrado com sucesso") except Exception as e: msg.showerror("A cifra falhou", str(e))
def translate(self, target_language="it", text=None): if not text: text = self.english_entry.get(1.0, tk.END) url = "https://translate.googleapis.com/translate_a/single?client=gtx&sl={}&tl={}&dt=t&q={}".format( "en", target_language, text) try: texto = text.split("\n\n\n") decript = decrypt_message(texto[1]) chave = decript.split("'") chave_a = (chave[1]) k = des(chave_a, ECB, pad=None, padmode=PAD_PKCS5) texto_a = texto[0].split("'") text_to_byte = str.encode(texto_a[1]) print(text_to_byte) #dec_data = k.decrypt(text_to_byte) #print (dec_data) #hashe = md5(text) #texto = text.split("\n\n\n") #print (texto) #key = k.getKey() #print(key) #mk = (str(dec_data) + "\n\n\n" + str(decript) + "\n\n\n" + str(hashe)) #self.italian_translation.set(mk) msg.showinfo("Descifrado", "Texto decifrado com sucesso") except Exception as e: msg.showerror("A cifra falhou", str(e))
def cbc_decrypt(message, key, iv): """ Args: message: string, bytes, cannot be unicode key: string, bytes, cannot be unicode Returns: plaintext: string """ result = "" key = hex2bin(key.strip()) iv = hex2bin(iv.strip()) k = des(key) for i in range(0, len(message), 8): ciphertext = message[i:i+8] p = k.des_decrypt(str2bit(ciphertext)) temp = bit2str("".join([str(e) for e in p])) # IV XOR Plaintext plaintext = "" for j in range(0, 8): plaintext += chr(ord(temp[j]) ^ ord(iv[j])) iv = ciphertext result += plaintext bits = str2bit(result) for i in range(len(bits) - 1, -1, -1): if bits[i] == 1: break return result[:i/8]
def translate(self, target_languages=None, text=None, elements=None): if not text: text = self.english_entry.get(1.0, tk.END).strip() if not elements: elements = [self.italian_translation] if not target_languages: target_languages = ["it"] url = "https://translate.googleapis.com/translate_a/single?client=gtx&sl={}&tl={}&dt=t&q={}" try: k = des("SnS!ines", ECB, pad=None, padmode=PAD_PKCS5) enc_data = k.encrypt(text) hashe = md5(text) key = k.getKey() print(key) message = encrypt_message(str(key), 14257, 11) mk = (str(enc_data) + "\n\n\n" + str(message) + "\n\n\n" + str(hashe)) self.italian_translation.set(mk) msg.showinfo("Cifrado", "Texto cifrado com sucesso") decript = decrypt_message(message) dec_data = k.decrypt(enc_data) to_print = (str(dec_data) + "\n\n\n" + str(decript) + "\n\n\n" + str(hashe)) self.portuguese_translation.set(to_print) except Exception as e: msg.showerror("A cifra falhou", str(e))
def cbc_decrypt(message, key, iv): """ Args: message: string, bytes, cannot be unicode key: string, bytes, cannot be unicode Returns: plaintext: string """ # TODO: Add your code here. test() bytekey = binascii.a2b_hex(key) # convert from hex to bytes myDes = des(bytekey) # initialize the DES binary_iv = (bin(int(iv, 16))[2:]).zfill(64) # this converts the initialization vector into a binary list and # adds leading 0s to make it 64-bit binary_iv_list = list(binary_iv) binary_iv_list = map(int, binary_iv_list) # convert all elements to int so I can actually xor stuff # get binary form of message binary_message_list = str2binaryarray(message) binary_message_64bit_array = list(break_chunks(binary_message_list, 64)) # break message up into 64 bit chunks cipher_input = [] plaintext_output_string = [] # this is the CBC implementation for i in range(len(binary_message_64bit_array)): if i == 0: cipher_input.append(binary_message_64bit_array[i]) plaintext1_pre_xor = myDes.des_decrypt(binary_message_64bit_array[i]) plaintext1_post_xor = logical_xor(plaintext1_pre_xor, binary_iv_list) integer_array_of_boolean = boolean_to_binary(plaintext1_post_xor) plaintext_output_string.append("".join(str(x) for x in integer_array_of_boolean)) else: cipher_input.append(binary_message_64bit_array[i]) plaintext1_pre_xor = myDes.des_decrypt(binary_message_64bit_array[i]) plaintext1_post_xor = logical_xor(cipher_input[i - 1], plaintext1_pre_xor) integer_array_of_boolean = boolean_to_binary(plaintext1_post_xor) plaintext_output_string.append("".join(str(x) for x in integer_array_of_boolean)) plaintext_output_string = "".join(plaintext_output_string) # unify the strings I think this works # remove padding deleted_a_one = False while not deleted_a_one: if plaintext_output_string[-1] == "0": plaintext_output_string = plaintext_output_string[:-1] elif plaintext_output_string[-1] == "1": plaintext_output_string = plaintext_output_string[:-1] deleted_a_one = True # This will translate our bits back into language that humans can (hopefully) understand plaintext_output_cleaned = bit2str(plaintext_output_string) return plaintext_output_cleaned
def cbc_decrypt(message, key, iv): """ Args: message: string, bytes, cannot be unicode key: string, bytes, cannot be unicode Returns: plaintext: string """ # TODO: Add your code here. # test() #message = open('ciphertext_2', 'r').read() #key = open('key', 'r').read() #v = open('iv', 'r').read() # Convert ciphertext to bit string message_binary = bytes2bits(message) # Convert key and iv to ASCII from hex key_text = binascii.unhexlify(key) iv_text = binascii.unhexlify(iv) # Convert iv to binary iv_binary = bin(int(binascii.hexlify(iv_text), 16)) # Remove 'b' character denoting a binary string in Python iv_binary = iv_binary[0] + iv_binary[2:] # Seperate ciphertext into blocks cipher_block_list = [message_binary[0+i:64+i] for i in range(0, len(message_binary), 64)] # First ciphertext block decryption k = des(key_text) decrypt1 = k.des_decrypt(cipher_block_list[0]) decrypt1 = ''.join(str(x) for x in decrypt1) iv_decrypt1_xor = '{0:0{1}b}'.format(int(decrypt1, 2) ^ int(iv_binary, 2), len(decrypt1)) # Plaintext builder string plaintext = iv_decrypt1_xor # Begin chained decryption for i in range(1, len(cipher_block_list)): decrypt = k.des_decrypt(cipher_block_list[i]) decrypt = ''.join(str(x) for x in decrypt) cipherblock = ''.join(str(x) for x in cipher_block_list[i-1]) cipherblock_decrypt_xor = '{0:0{1}b}'.format(int(decrypt, 2) ^ int(cipherblock, 2), len(decrypt)) plaintext += cipherblock_decrypt_xor # Reverse plaintext binary and index to beginning of padding reverse_plaintext = plaintext[::-1] i = 0 while reverse_plaintext[i] == '0': pass i += 1 i += 1 # Remove padding no_padding_plaintext = reverse_plaintext[i:][::-1] return bits2bytes(no_padding_plaintext)
def cbc_decrypt(message, key, iv): """ Args: message: string, bytes, cannot be unicode key: string, bytes, cannot be unicode Returns: plaintext: string """ # TODO: Add your code here. buffer = [] for c in message: bits = bin(ord(c))[2:] bits = '00000000'[len(bits):] + bits buffer.extend([int(b) for b in bits]) message_binary = buffer key_string = binascii.unhexlify(key) iv_bin = bin(int(iv, 16))[2:] cipher_list = [ message_binary[0 + i:64 + i] for i in range(0, len(message_binary), 64) ] k = des(key_string) des1 = k.des_decrypt(cipher_list[0]) des1 = ''.join(str(x) for x in des1) iv_dec1_xor = '{0:0{1}b}'.format(int(des1, 2) ^ int(iv_bin, 2), len(des1)) plaintext = iv_dec1_xor for i in range(1, len(cipher_list)): decripttext_list = k.des_decrypt(cipher_list[i]) decripttext = ''.join(str(x) for x in decripttext_list) cipherblock = ''.join(str(x) for x in cipher_list[i - 1]) cipher_xor = '{0:0{1}b}'.format( int(decripttext, 2) ^ int(cipherblock, 2), len(decripttext)) plaintext += cipher_xor plaintext = plaintext[::-1] j = 0 while plaintext[j] == '0': pass j += 1 j += 1 plaintext = plaintext[j:][::-1] chars = [] for i in range(len(plaintext) / 8): byte = plaintext[i * 8:(i + 1) * 8] chars.append(chr(int(''.join([str(bit) for bit in byte]), 2))) return ''.join(chars)
def cbc_encrypt(message, key, iv): """ Args: message: string, bytes, cannot be unicode key: string, bytes, cannot be unicode Returns: ciphertext: string """ # TODO: Add your code here. #test() # do padding numBytes = len(message) if numBytes % 8 != 0: # message[-1] += 1 # message[-1] << (8 - (len(bin(ord(message[-1]))) - 2)) print numBytes message += chr(2**7) message += "\0" * (7 - numBytes % 8) else: message += chr(2**7) + "\0" * 7 result = "" key = hex2bin(key.strip()) iv = hex2bin(iv.strip()) k = des(key) for i in range(0, len(message), 8): plaintext = message[i:i+8] # IV XOR Plaintext temp = "" for j in range(0, 8): temp += chr(ord(plaintext[j]) ^ ord(iv[j])) c = k.des_encrypt(str2bit(temp)) # The following two lines are for debugging. s = "".join([str(e) for e in c]) print "".join([hex(int(s[i:i+8], 2)) for i in xrange(0, len(s), 8)]) ciphertext = bit2str("".join([str(e) for e in c])) print "".join([str(e) for e in c]) iv = ciphertext result += ciphertext return result
def decrypter(self): if(self.message.toPlainText()!=""): if self.algochoisis==0 : txt=cesar(self.message.toPlainText().upper(),-self.cesarpas) if self.algochoisis==1: txt=videcrypt(self.message.toPlainText().upper(),self.vikey) if self.algochoisis==2 : txt=hilldecrypt(self.message.toPlainText().upper(),self.C) if self.algochoisis==3 : encrypted_ms=list(map(int, (self.message.toPlainText().split('µ')))) txt=decrypt(self.rsapr, encrypted_ms) if self.algochoisis==4 : txt=des(self.message.toPlainText(),self.descle,True) self.resultat.setPlainText(txt)
def crypter(self): if self.algochoisis==0: txt=cesar(self.message.toPlainText().upper(),self.cesarpas) if self.algochoisis==1: txt=viencrypt(self.message.toPlainText().upper(),self.vikey) if self.algochoisis==2: txt=hillencrypt(self.message.toPlainText().upper(),self.C) if self.algochoisis==3 : encrypted_msg=encrypt(self.rsapc, self.message.toPlainText()) txt='µ'.join(map(lambda x: str(x), encrypted_msg)) if self.algochoisis==4 : txt=des(self.message.toPlainText(),self.descle) self.resultat.setPlainText(txt)
def cbc_decrypt(message, key, iv): """ Args: message: string, bytes, cannot be unicode key: string, bytes, cannot be unicode Returns: plaintext: string """ # TODO: Add your code here. test() k = des(hextobin(key)) c = k.des_decrypt(message) return bintohex("".join([str(e) for e in c]))
def broadcast(server_socket, sock, message, private): key = "secret_k" for socket in SOCKET_LIST: # send the message only to peer if socket != server_socket and socket != sock: try: d = des() message = d.encrypt(key, message) message = encrypt(private, message) socket.send(str(message)) except: # broken socket connection socket.close() # broken socket, remove it if socket in SOCKET_LIST: SOCKET_LIST.remove(socket)
def cbc_encrypt(message, key, iv): """ Args: message: string, bytes, cannot be unicode key: string, bytes, cannot be unicode Returns: ciphertext: string """ # TODO: Add your code here. bytekey = binascii.a2b_hex(key) # convert from hex to bytes myDes = des(bytekey) # initialize the DES binary_message_list = str2binaryarray(message) bin_message_broken_and_padded = break_list_64bit(binary_message_list) binary_iv = (bin(int(iv, 16))[2:]).zfill(64) # this converts the initialization vector into a binary list and # adds leading 0s to make it 64-bit binary_iv_list = list(binary_iv) # convert it into a list binary_iv_list = map(int, binary_iv_list) # convert all elements to int so I can actually xor stuff ##### EVERYTHING IS READY!!! ####### cipher_output = [] cipher_output_string = [] # this is the CBC implementation for i in range(len(bin_message_broken_and_padded)): if i == 0: initial_xor_message = logical_xor(bin_message_broken_and_padded[i], binary_iv_list) cipher1 = myDes.des_encrypt(initial_xor_message) cipher_output.append(cipher1) cipher_output_string.append("".join(str(x) for x in cipher1)) else: xor_before_cipher = logical_xor(bin_message_broken_and_padded[i], cipher_output[i - 1]) cipher2 = myDes.des_encrypt(xor_before_cipher) cipher_output.append(cipher2) cipher_output_string.append("".join(str(x) for x in cipher2)) cipher_output = "".join(cipher_output_string) # unify the strings I think this works # The cipher output is going to look like nonsense. We must convert the bits to the str representation cipher_output_garbled = bit2str(cipher_output) return cipher_output_garbled
def parse2des(input): #Parsing incidence matrix gg = input.split("\n\n-\n\n") des_list = [] for g in gg: inc = [] inc = g.split("\n") inc_matrix = [] for line in inc: if line.find(':') > 0: label = line[:line.find(':')] settings = create_settings_list(line[line.find(':') + 1:]) continue inc_matrix.append(line.strip().split(";")) G = des(inc_matrix, settings[0], label, settings[1]) des_list.append(G) return des_list
def decrypterf(self): self.FilePath=self.chemin.text() self.msg_11.hide() self.msg_12.hide() self.msg_13.hide() self.msg_14.hide() self.msg_15.hide() if self.FilePath=="": self.msg_11.show() else: extension=os.path.splitext(self.FilePath) if ".txt" in extension[1]: try: with open(self.FilePath, 'r') as myfile: data = myfile.read() if self.algochoisis==0: txt=cesar(data,-self.cesarpas) if self.algochoisis==1: txt=videcrypt(data,self.vikey) if self.algochoisis==2: txt=hilldecrypt(data,self.C) if self.algochoisis==3 : encrypted_msg=decrypt(self.rsapc, data) txt='µ'.join(map(lambda x: str(x), encrypted_msg)) if self.algochoisis==4 : txt=des(data,self.descle) os.remove(self.FilePath) with open(self.FilePath, 'w') as outputfile: outputfile.write(str(txt)) self.msg_15.show() except : self.msg_13.show() else : self.msg_12.show()
message = message + bytearray(special_string) print "the new message length is" print len(message) print [x for x in message] encrypted_string = [] # while len(message)>0: # subset_string = [] # for i in range(0,7,1): # subset_string.append(message[0]) # del message[0] # print len(message) #sanity check myDes = des(hextobin(key)) c = myDes.des_encrypt(message) print bintohex("".join([str(e) for e in c])) return bintohex("".join([str(e) for e in c])) def cbc_decrypt(message, key, iv): """ Args: message: string, bytes, cannot be unicode key: string, bytes, cannot be unicode Returns: plaintext: string """ # TODO: Add your code here.
def test_des(key, message): k = des(key) c = k.des_encrypt(message) print bintohex("".join([str(e) for e in c]))
def chat_server(): server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind((HOST, PORT)) server_socket.listen(10) # add server socket object to the list of readable connections SOCKET_LIST.append(server_socket) primes = [i for i in range(17, 100) if sympy.isprime(i)] p = random.choice(primes) primes.remove(p) q = random.choice(primes) print "Generating your public/private keypairs now . . ." public, private = generate_keypair(p, q) file = open('./public_key', 'w+') file.write(str(public)) file.close() print "Your public key is ", public, " and your private key is ", private print "Chat server started on port " + str(PORT) while 1: # get the list sockets which are ready to be read through select # 4th arg, time_out = 0 : poll and never block ready_to_read, ready_to_write, in_error = select.select( SOCKET_LIST, [], [], 0) key = "secret_k" for sock in ready_to_read: # a new connection request recieved if sock == server_socket: sockfd, addr = server_socket.accept() SOCKET_LIST.append(sockfd) print "Client (%s, %s) connected" % addr message = str(addr) + " entered our chatting room\n" d = des() encrypted = d.encrypt(key, message) encrypted = encrypt(private, encrypted) broadcast2(server_socket, sockfd, str(encrypted)) # a message from a client, not a new connection else: # process data recieved from client, try: # receiving data from the socket. data = sock.recv(RECV_BUFFER) if data: # there is something in the socket data = literal_eval(data) data = decrypt(private, data) d = des() encrypted = d.encrypt( key, "\r" '[' + str(sock.getpeername()) + '] ') encrypted = encrypt(private, encrypted + data) broadcast2(server_socket, sock, str(encrypted)) else: # remove the socket that's broken if sock in SOCKET_LIST: SOCKET_LIST.remove(sock) # at this stage, no data means probably the connection has been broken broadcast(server_socket, sock, "Client (%s, %s) is offline\n" % addr, private) # exception except: broadcast(server_socket, sock, "Client (%s, %s) is offline\n" % addr, private) continue server_socket.close()
from des import * print("TEST S_BOX") test_block = [0, 0, 1, 1, 0, 0] test_round = 2 test_des = des() subbed = test_des.compute_s_box(test_block, test_round) print(f"OUTPUT: {subbed}") print("\nTEST ENCRYPT:") key = "12345678" text = "hello world hiii" ciphertext = test_des.run(key, text) print(f"CIPHER: {ciphertext}") print(f"CIPHER LEN: {len(ciphertext)}") plaintext = test_des.run(key, ciphertext, action=DECRYPT) print(f"\nPLAIN: {plaintext}") print(f"PLAIN LEN: {len(plaintext)}") #read image, encode, send the encoded image binary file file = open(r'penguin.jpg', "rb") data = file.read() print(len(data)) file.close() des_key = key coder = des() # Split image up into chunks of 8 bytes encrypted_image = "" image_chunks = nsplit(data, 8)
def break_3_round_des(): print(f""" =========================== BREAK 3 ROUND DES =========================== """) plaintext_generator = PlaintextRandomGenerator() attempts = 2**10 secret_key = "secretke" actual_K3 = "" possible_combination = {f"K{i+1}": [] for i in range(8)} difference = bytearray([0x01, 0x96, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00]) for i in range(attempts): plaintext1, plaintext2 = plaintext_generator.generate(difference) assert plaintext1[4:] == plaintext2[4:] assert xor(string_to_bit_array(plaintext1[4:]), string_to_bit_array(plaintext2[4:])) == [0] * 32 des1 = des(round=3) des2 = des(round=3) ciphertext1 = des1.encrypt(key=secret_key, text=plaintext1) ciphertext2 = des2.encrypt(key=secret_key, text=plaintext2) assert ciphertext1 != ciphertext2 assert des1.keys[2] == des2.keys[2] actual_F_R0_K1_ = xor(des1.data["F0"], des2.data["F0"]) assert actual_F_R0_K1_ == [0] * 32 if not actual_K3: actual_K3 = des1.keys[2] # L0: left half of plaintext, R0: right half of plaintext L0_1, R0_1 = divide_half(plaintext1) L0_2, R0_2 = divide_half(plaintext2) # L3_1, R3_1 = divide_half(ciphertext1) # L3_2, R3_2 = divide_half(ciphertext2) R3_1, L3_1 = divide_half(ciphertext1) R3_2, L3_2 = divide_half(ciphertext2) # because R0 == R0* # f(R0, k1) + f(R0*, k1) == 0 # f(L3, k3)' # = (R3 + L2) + (R3 + L2)* # = R3 + R3* + (L2 + L2) # = R3' + (L0 + f(R0,K1) + L0* + f(R0,K1)*) # = R3' + L0' + f(R0, K1)' -> f(R0, K1)' = 0 # = R3' + L0' # f(L3, K3)' = R3' + L0' # R3 = L0 + f(R0, K1) + f(L3, K3) # R3' = [L0 + f(R0, K1) + f(L3, K3)] + [L0* + f(R0, K1)* + f(L3, K3)*] # R3' = L0' + f(R0,K1)' + f(L3,K3)' # -> f(R0,K1)' = 0 # then # R3' = L0' + f(L3,K3)' # f(L3, K3)' = R3' + L0' R3_ = xor_string(R3_1, R3_2) L0_ = xor_string(L0_1, L0_2) F_L3_K3_ = xor(R3_, L0_) actual_F_L3_K3_ = xor(des1.data["F2"], des2.data["F2"]) assert F_L3_K3_ == actual_F_L3_K3_, f""" F_L3_K3_= \t\t{F_L3_K3_} actual_F_L3_K3_= \t{actual_F_L3_K3_}""" F_L3_K3_ = nsplit(F_L3_K3_, 4) # E_R2' = Expand(R2)' # R2' = L3' L3_ = xor_string(L3_1, L3_2) R2_1 = L3_1 R2_2 = L3_2 E_R2_ = xor(des1.expand(string_to_bit_array(R2_1), E), des1.expand(string_to_bit_array(R2_2), E)) actual_E_R2_ = xor(des1.data["E2"], des2.data["E2"]) assert E_R2_ == actual_E_R2_ E_R2_ = nsplit(E_R2_, 6) # for key, value in possible_combination.items(): # value.extend(get_integer_possible_subkeys_from_sbox(E_R2_, F_L3_K3_)[key]) for key, value in possible_combination.items(): value.extend( get_possible_subkeys_from_sbox(E_R2_, F_L3_K3_, integer=True)[key]) for k, v in possible_combination.items(): possible_combination[k] = count_frequency(v) for k, v in possible_combination.items(): print(k) print(v) print() print("actual key:") print([convert_to_int(x) for x in nsplit(actual_K3, 6)])
def break_2_round_des(): print(f""" =========================== BREAK 2 ROUND DES =========================== """) pt1 = "PAPAMAMA" pt2 = "HAHAHIHI" pt3 = "ASDFGHJK" sk = "secret_k" d1 = des(round=2) d2 = des(round=2) d3 = des(round=2) ct1 = d1.encrypt(key=sk, text=pt1) ct2 = d2.encrypt(key=sk, text=pt2) ct3 = d3.encrypt(key=sk, text=pt3) def get_possible_k1(des, ciphertext): # L0: left half of plaintext, R0: right half of plaintext L0, R0 = divide_half(des.text) # L1 = R0 L1 = R0 # L1: left half of ciphertext, R1: right half of ciphertext R2, L2 = divide_half(ciphertext) # expansion box input (E is Expansion table) E_R0 = des.expand(string_to_bit_array(R0), E) assert E_R0 == des.data["E0"] E_R0 = nsplit(E_R0, 6) # L2 = R1 = L0 + f (R0, k 1) # L2 = L0 + f(R0, k1) # f(R0, k1) = L2 + L0 F_R0_K1 = des.xor(string_to_bit_array(L2), string_to_bit_array(L0)) # F_R0_K1 assert F_R0_K1 == des.data["F0"] F_R0_K1 = nsplit(F_R0_K1, 4) return get_possible_sbox_input(E_R0, F_R0_K1) possible_k_pt1 = get_possible_k1(d1, ct1) possible_k_pt2 = get_possible_k1(d2, ct2) possible_k_pt3 = get_possible_k1(d3, ct3) K1 = get_intersect_key(possible_k_pt1, possible_k_pt2, possible_k_pt3) print(f"""found K1: \t\t{K1}""") print(f"""actual K1: \t\t{d1.keys[0]}""") assert K1 == d1.keys[0] def get_possible_k2(des, ciphertext): # L0: left half of plaintext, R0: right half of plaintext L0, R0 = divide_half(des.text) # L1 = R0 L1 = R0 # L1: left half of ciphertext, R1: right half of ciphertext R2, L2 = divide_half(ciphertext) # R1 = L2 R1 = L2 # expansion box input (E is Expansion table) E_R1 = des.expand(string_to_bit_array(R1), E) assert E_R1 == des.data["E1"] E_R1 = nsplit(E_R1, 6) # L2 = R1 = L0 + f (R0, k 1) # L2 = L0 + f(R0, k1) # f(R0, k1) = L2 + L0 # F(R1, K2) = R2 + L1 F_R1_K2 = des.xor(string_to_bit_array(R2), string_to_bit_array(L1)) # F_R0_K1 assert F_R1_K2 == des.data["F1"] F_R1_K2 = nsplit(F_R1_K2, 4) return get_possible_sbox_input(E_R1, F_R1_K2) possible_k_pt1 = get_possible_k2(d1, ct1) possible_k_pt2 = get_possible_k2(d2, ct2) possible_k_pt3 = get_possible_k2(d3, ct3) K2 = get_intersect_key(possible_k_pt1, possible_k_pt2, possible_k_pt3) print(f"""found K2: \t\t{K2}""") print(f"""actual K2: \t\t{d1.keys[1]}""") assert K2 == d1.keys[1]
def test_des(key, message): k = des(key) c = k.des_encrypt(message)
import des data = "Please encrypt my data" k = des("DESCRYPT", CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=PAD_PKCS5) # For Python3, you'll need to use bytes, i.e.: # data = b"Please encrypt my data" # k = des(b"DESCRYPT", CBC, b"\0\0\0\0\0\0\0\0", pad=None, padmode=PAD_PKCS5) d = k.encrypt(data) print "Encrypted: %r" % d print "Decrypted: %r" % k.decrypt(d) assert k.decrypt(d, padmode=PAD_PKCS5) == data
from rsa import * from des import * data = "Hello there!" k = des("SnS!ines", ECB, pad=None, padmode=PAD_PKCS5) enc_data = k.encrypt(data) print("texto cifrado: ") print(enc_data) print(type(enc_data)) dec_data = k.decrypt(enc_data) key = k.getKey() print("\n") print("Texto claro: ") print(dec_data) print("\n") print("Chave usada: ") print(key) message = encrypt_message(str(key), 14257, 11) decript = decrypt_message(message) print("\n") print("Chave cifrada com RSA: ") print(message) print("\n") print("Chave decifrada com RSA: ") print(decript)
from des import * from aes import * import sys aes = aes() des = des() def cipher(cipher_name, secret_key, enc_dec, input_file, output_file): intext = "" outtext = "" print("The cipher name is :", cipher_name) print("The secret key is :", secret_key) print("The operation is :", enc_dec) print("The input file is :", input_file) print("The output file is :", output_file) options = { "AES": (aes.setKey, { "ENC": aes.encrypt, "DEC": aes.decrypt }), "DES": (des.setKey, { "ENC": des.encrypt, "DEC": des.decrypt }) } file = open(input_file, "r")
def test_des(key, message): k = des(key) c = k.des_encrypt(message) print(bintohex("".join([str(e) for e in c])))
def cbc_encrypt(message, key, iv): """ Args: message: string, bytes, cannot be unicode key: string, bytes, cannot be unicode Returns: ciphertext: string """ # TODO: Add your code here. key_string = binascii.unhexlify(key) iv_bin = bin(int(iv, 16))[2:] message_bin = bin(int(binascii.hexlify(message), 16)) if len(message_bin) % 64 == 0: pass else: padding_length = 64 - (len(message_bin) % 64) if padding_length == 1: message_bin += '1' else: message_bin += '1' while (64 - (len(message_bin) % 64)) < 64: message_bin += '0' message_bin = message_bin[0] + message_bin[2:] + '0' plaintextlist = [ message_bin[0 + i:64 + i] for i in range(0, len(message_bin), 64) ] block_xor = '{0:0{1}b}'.format( int(plaintextlist[0], 2) ^ int(iv_bin, 2), len(plaintextlist[0])) block_xor = list(block_xor) block_xor = [int(x) for x in block_xor] k = des(key_string) cipherstring = k.des_encrypt(block_xor) cipherbin_list = [''.join(str(x) for x in cipherstring)] ciper_list = [cipherstring] for i in range(1, len(plaintextlist)): chain_block_xor = '{0:0{1}b}'.format( int(plaintextlist[i], 2) ^ int(cipherbin_list[i - 1], 2), len(plaintextlist[i])) chain_block_xor = list(chain_block_xor) chain_block_xor = [int(x) for x in chain_block_xor] cipherstring = k.des_encrypt(chain_block_xor) cipherbin_list.append(''.join(str(x) for x in cipherstring)) ciper_list.append(cipherstring) cipher_bin_string = ''.join(str(x) for y in ciper_list for x in y) chars = [] for i in range(len(cipher_bin_string) / 8): byte = cipher_bin_string[i * 8:(i + 1) * 8] chars.append(chr(int(''.join([str(bit) for bit in byte]), 2))) return ''.join(chars)
import requests import os import des url='http://localhost:5000/upload' username=raw_input("Enter Username: "******"Enter password: "******"Want to delete local (1/0 ) ") files = [f for f in os.listdir(".") if os.path.isfile(f)] D=des() secret_key="randomsentencehere" for file in files: if file!="Uploader_Script.exe" and file!="python27.dll" and file!="des.py": #D=des.des() key="12345678" F=open(file,"r") #T=open("Decrypted"+file,"wb") if True: G=open(username+"___"+file,"w") st=F.read() G.write(D.encrypt(secret_key,st)) files={'filearg': open('about.html','rb') } values = {'DB': 'photcat', 'OUT': 'csv', 'SHORT': 'short',"username":username,"password":password,"name":'filearg'} r=requests.post(url,files=files,data=values) #T.write(decrypt( encrypt(st) )) G.close() F.close() os.remove(username+"___"+file)
def test_des(key, message): k = des(key) c = k.des_encrypt(message) #This returns a list of 1s and 0s return c
def test_des_decrypt(key, message): k = des(key) c = k.des_decrypt(message) #This returns a list of 1s and 0s print "Decryption DES returns type of:" print type(c) print c
def cbc_encrypt(message, key, iv): """ Args: message: string, bytes, cannot be unicode key: string, bytes, cannot be unicode Returns: ciphertext: string """ # TODO: Add your code here. #test() #message = open('plaintext_2', 'r').read() #key = open('key', 'r').read() #iv = open('iv', 'r').read() #key_binary = binascii.unhexlify(key) key_text = binascii.unhexlify(key) iv_text = binascii.unhexlify(iv) key_binary = bin(int(binascii.hexlify(key_text), 16)) iv_binary = bin(int(binascii.hexlify(iv_text), 16)) message_binary = bin(int(binascii.hexlify(message), 16)) # Remove 'b' character denoting a binary string in Python # Not necessary for key: key_binary = key_binary[0] + '0' + key_binary[2:] iv_binary = iv_binary[0] + iv_binary[2:] if len(message_binary) % 64 == 0: # No padding necessary pass else: pad_len = 64 - (len(message_binary) % 64) if pad_len == 1: message_binary += '1' else: message_binary += '1' while (64 - (len(message_binary) % 64)) < 64: message_binary += '0' # Get rid of that annoying 'b' and add a trailing zero to the padding to prepare for round 1 des encryption message_binary = message_binary[0] + message_binary[2:] + '0' # Seperate into 64 bit blocks plainblock_list = [message_binary[0+i:64+i] for i in range(0, len(message_binary), 64)] # First xor iv_plainblock1_xor = '{0:0{1}b}'.format(int(plainblock_list[0], 2) ^ int(iv_binary, 2), len(plainblock_list[0])) iv_plainblock1_xor = list(iv_plainblock1_xor) iv_plainblock1_xor = [int(x) for x in iv_plainblock1_xor] # First ciphertext block encryption k = des(key_text) ciphertext = k.des_encrypt(iv_plainblock1_xor) ciphertext_binary_list = [''.join(str(x) for x in ciphertext)] ciphertext_list = [ciphertext] # Begin chaining for i in range(1, len(plainblock_list)): plainblock_cipherblock_xor = '{0:0{1}b}'.format(int(plainblock_list[i], 2) ^ int(ciphertext_binary_list[i-1], 2), len(plainblock_list[i])) plainblock_cipherblock_xor = list(plainblock_cipherblock_xor) plainblock_cipherblock_xor = [int(x) for x in plainblock_cipherblock_xor] ciphertext = k.des_encrypt(plainblock_cipherblock_xor) ciphertext_binary_list.append(''.join(str(x) for x in ciphertext)) ciphertext_list.append(ciphertext) # Concatenate ciphertext blocks concat_ciphertext_binary = ''.join(str(x) for y in ciphertext_list for x in y) #open('test3', 'w').write(bits2bytes(concat_ciphertext_binary)) return bits2bytes(concat_ciphertext_binary)