def handle_request(self, request: Request) -> (str, bool): if request.data_input and not request.input_file: return self.next_handler.handle_request(request) key = DesKey(request.key.encode('utf-8')) try: with open(request.input_file, 'r') as file_object: request.result = key.decrypt(ast.literal_eval( file_object.read()), padding=True) if self.next_handler is None: return "", True return self.next_handler.handle_request(request) except FileNotFoundError: return f"{request.input_file} not exist!", False
def client_program(): host = socket.gethostname() port = 12345 # socket server port number # create the socket in the client side s = socket.socket() s.connect((host, port)) # connect to the server desFile = open("deskey.txt", "r") hmacFile = open("hmackey.txt", "r") desKeystr = desFile.read() key = DesKey(desKeystr.encode('utf-8')) # create a key hmacKey = hmacFile.read() hmacKeystr = hmacFile.read() byteHmacKey = bytes(hmacKeystr, encoding='utf8') digest_maker = hmac.new(byteHmacKey, msg=None, digestmod=hashlib.sha1) message = input(" -> ") while message.lower().strip() != 'bye': con = key.encrypt(message.encode('utf-8'), padding=True) digest_maker.update(message.encode()) digest = digest_maker.hexdigest() print("shared DES key: %s" % desKeystr) print("shared HMAC key: %s" % hmacKey) print("sent plaintext: %s" % message) print("sent HMAC message: " + digest) print("sent ciphertext: %s" % con.decode('utf-8', 'ignore')) print("===========================================================") s.send(con) data = s.recv(1024) # receive response print("received ciphertext: %s" % data.decode('utf-8', 'ignore')) pt = key.decrypt(data, padding=True).decode() print("received plaintext: %s" % pt) digest_maker.update(data) digest = digest_maker.hexdigest() print("received HMAC message: " + digest) print("calculated HMAC: " + digest) print("HMAC Verified") print("===========================================================") message = input(" -> ") # again take input s.close() # close the connection desFile.close() hmacFile.close()
def main(): server_address = ('localhost', 9999) # authentication server address ss_id = '1efeggrvv' # id of service server ss_address = ('localhost', 5000) # address of service server tgt_path = 'tgt' data_path = 'data.json' login = input('login: '******'password: '******'utf-8') # create key from hash of password m = hashlib.sha256() m.update(password) key_c = DesKey(m.digest()[:8]) with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock: is_authenticated = is_auth(data_path, tgt_path) # Loop while we are not authorized while True: # skip authentication if we already have tgt if is_authenticated: with open('data.json') as f1, open('tgt', 'rb') as f2: data = json.load(f1) tgt = f2.read() else: # AS_REQ as_req(sock, server_address, login, key_c) # AS_REP data, tgt = as_rep(sock, key_c, tgt_path, data_path) key_c_tgs, tgs_address, p1 = data # key_c_tgs is a string key key_c_tgs = DesKey(key_c_tgs.encode('utf-8')) # tgs_address is a list (need a tuple) tgs_address = tuple(tgs_address) # TGS_REQ tgs_req(sock, tgs_address, login, ss_id, tgt, key_c_tgs) # TGS_REP tgs_rep_data = tgs_rep(sock, key_c_tgs) if tgs_rep_data: break else: is_authenticated = False data_tgs, st = tgs_rep_data key_c_ss, ss, p2 = data_tgs # key_c_ss is a string key key_c_ss = DesKey(key_c_ss.encode('utf-8')) # SS_REQ t4 = int(dt.datetime.utcnow().timestamp()) ss_req(sock, ss_address, login, t4, st, key_c_ss) # SS_REP t_c1 = sock.recv(1024) t_c1 = int(key_c_ss.decrypt(t_c1)) if t_c1 - t4 == 1: print('Success authorization :)') else: print('Server is not authorized!')
def decrypt_ultravnc(password): key = bytes.fromhex('E84AD660C4721AE0') des = DesKey(key) input_password = password if len(input_password) % 8 == 0: clear = des.decrypt(bytes.fromhex(password)) #print(bytes.fromhex(password)) #print(clear) return clear.decode('utf-8') else: padding = len(input_password) % 8 padded_password = input_password + ('00' * padding) clear = des.decrypt(bytes.fromhex(padded_password)) print(clear) sys.exit() return clear.decode('utf-8')
def handle_request(self, request: Request) -> (str, bool): """ Decrypts the data with the key. Decryption can fail if the data is not valid (divisible by 8). :param request: Request from cmd line args :return: (str, bool) str: a message, bool True if validation is passed """ key = DesKey(request.key.encode('utf-8')) data = request.data_input if len(data) % 8 != 0: return "length of the message should be divisible by 8, cannot be decrypted", False request.result = key.decrypt(data, padding=True) if request.result == b"": return f"Data cannot be decrypted with key {request.key}", False if self.next_handler: return self.next_handler.handle_request(request) else: return "", True
def encode(Blocks, Keys): max_len = len(Blocks) if len(Blocks) > len(Keys) else len(Keys) enc_blocks = [] for i in range(0, max_len): key = DesKey(Keys[i % len(Keys)].decode('hex')) enc_block = key.encrypt(pad(Blocks[i % len(Blocks)])) print "val = ", int(SECRET[i % len(SECRET)]) if int(SECRET[i % len(SECRET)]) == 1: enc_block = key.encrypt(enc_block) enc_blocks.append(enc_block.encode('hex')) return enc_blocks
def handle_request(self, command: Request) -> (bool, str): """ It conveerts the Key into DesKey and decrypt the data, assigns it to a result attribute of the request. :param command: a Request :return: a tuple where the first element is a string stating the outcome and the reason, and the second a bool indicating successful handling of the form or not. """ print("Decrypting...") try: key = DesKey(command.key.encode("utf-8")) command.result = key.decrypt(command.data, padding=True).decode("utf-8") except Exception as e: return False, f"Decryption Failed!" else: return self.pass_handler(command)
def tgs_rep(sock: socket, key_c_tgs: DesKey): data_tgs = sock.recv(1024) if b'Error' in data_tgs: print(data_tgs.decode('utf-8')) return None st = sock.recv(1024) data_tgs = key_c_tgs.decrypt(data_tgs) data_tgs = json.loads(data_tgs) return data_tgs, st
def worker_func(i): # Simply computes the sum of the i-th row of the input matrix X # X_np = np.frombuffer(var_dict['X'], dtype=np.uint8).reshape( # var_dict['X_shape']) # time.sleep(1) # Some heavy computations # return np.asscalar(np.sum(X_np[i, :])) des = DesKey(bytes(var_dict['key'], encoding="utf-8")) img_array = np.frombuffer(var_dict['X'], dtype=np.uint8).reshape(var_dict['X_shape']) if var_dict['mode'] == 'e': enc_x = des.encrypt(img_array[i].tobytes(), padding=False) else: enc_x = des.decrypt(img_array[i].tobytes(), padding=False) enc_x = np.frombuffer(enc_x, dtype=np.uint8).reshape( (var_dict['X_shape'][1], var_dict['X_shape'][2])) return enc_x
def handle_request(self, request) -> None: # Set up decryption key bytes_key = request.key.encode() key0 = DesKey(bytes_key) if request.data_input: print("Decrypting request from direct string... ...") request.result = ast.literal_eval(r"{0}".format( request.data_input)) else: with open(request.input_file, "rb+") as input_file: request.result = input_file.read() request.result = key0.decrypt(request.result, padding=True).decode('utf-8') if self.next_handler: self.next_handler.handle_request(request) else: return
class MyUDPHandler(socketserver.BaseRequestHandler): def handle(self): data = self.request[0].strip() socket = self.request[1] print(f"{self.client_address[0]} wrote:\n{data}") if data == b'AS_REQ': user_login = socket.recv(1024).decode('utf-8') t1 = socket.recv(1024) print(user_login, t1) if user_login not in USER_DB: socket.sendto(b'Error: You are not in DB', self.client_address) return password = USER_DB[user_login].encode('utf-8') m = hashlib.sha256() m.update(password) # create key self.key_c = DesKey(m.digest()[:8]) t1_kc = self.key_c.decrypt(t1) delta = dt.datetime.utcnow() - dt.datetime.fromtimestamp( int.from_bytes(t1_kc, 'big')) if delta.total_seconds() / 60 > 5: socket.sendto( b'Error: Timezones must be identical or check your password', self.client_address) return # AS_REP # key generation: # https://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits/23728630#23728630 key_c_tgs = ''.join( secrets.choice(string.ascii_letters + string.digits) for _ in range(8)) p1 = 8 # hours t_kdc = int(dt.datetime.utcnow().timestamp()) data_kc = json.dumps([key_c_tgs, TGS_ADDRESS, p1]).encode('utf-8') data_kc = self.key_c.encrypt(data_kc) socket.sendto(data_kc, self.client_address) tgt = json.dumps([user_login, key_c_tgs, p1, t_kdc]).encode('utf-8') tgt = K_TGS.encrypt(tgt) socket.sendto(tgt, self.client_address)
def receiveResponse(): ciphertext_received = s.recv(1024) if ciphertext_received != "": print("Ciphertext received from server:", end=' ') print(ciphertext_received) f = open("DESkey.txt", "r") des_key_from_file = str.encode(f.read()) des_key0 = DesKey(des_key_from_file) decrypted_text = des_key0.decrypt(ciphertext_received, padding=True) # use regex to pull message from the decrypted text received pattern = "b\"(.*?)b'" substring = re.search(pattern, str(decrypted_text)).group(1) print("received message: " + substring) # use regex to pull received hmac from the decrypted text received, remove duplicate backslashes pattern2 = "b\"" + substring + "(.*?)" + "\"" substring2 = re.search(pattern2, str(decrypted_text)).group(1) substring2 = substring2.replace('\\\\', '\\') print("received hmac: " + substring2) # calculate own HMAC with the message and shared secret HMAC key f2 = open("HMACKey.txt", "r") hmac_key_from_file = f2.read() hmac_key_bytes_from_file = bytes(hmac_key_from_file, 'latin-1') substring_bytes = bytes(substring, 'latin-1') digest_maker = hmac.new(hmac_key_bytes_from_file, substring_bytes, digestmod='MD5') hashed_message = str(digest_maker.digest()) print("calculated hmac: " + hashed_message) # verify the generated hmac and the received hmac if substring2.find(hashed_message) != -1: print("HMAC VERIFIED") else: print("HMAC NOT VERIFIED") print("************************************************")
def handle_request(self, request_: Request) -> (str, bool): """ Decrypts either the given string or file :param request_: a Request :return: a tuple """ print("Decrypt Reading") key = DesKey(request_.key.encode('utf-8')) if request_.data_input: data = r"{0}".format(request_.data_input) data = ast.literal_eval(data) request_.result = key.decrypt(data, padding=True).decode('utf-8') else: with open(request_.input_file, "r") as file: data = file.read() data = ast.literal_eval(data) request_.result = key.decrypt(data, padding=True).decode('utf-8') if not self.next_handler: return "", True return self.next_handler.handle_request(request_)
class DES_Crypt(): def __init__(self, key: str, text: str): """ :key: private key, will be encoded into bytes :text: plaintext, will be encoded into bytes """ self.key = DesKey(bytes(key.encode('utf-8'))) self.text = bytes(text.encode('utf-8')) @MyTools.info("T encrypt") def encrypt(self): self.encrypted = self.key.encrypt(self.text, padding=True) return self.encrypted @MyTools.info("T decrypt") def decrypt(self): self.decrypted = self.key.decrypt(self.encrypted, padding=True) return self.decrypted def is_single(self): return self.key.is_single()
def __init__( self, mode = "ECB", key = "some key", block_size = 8, IV = "TWOBUCKS", s = 5, ctr = "7" ): self.mode = mode self.key = key self.block_size = block_size self.IV = IV self.ctr = ctr self.s = s self.encoding = 'cp437' self.key_obj = DesKey(self.key.encode(self.encoding)) self.IV = self.IV.ljust(len(self.IV)+self.block_size\ - (len(self.IV)+self.block_size)%self.block_size, 'X') if len(self.IV)%self.block_size else self.IV self.ctr = self.ctr.zfill(self.block_size)
def encrypt_txt(): """ Function to retrieve user inputted text and convert it to an encrypted string of bytes. - Function also instantiates the decrypt button & positions it to the window """ key = ent_choose_key.get() # Get key from user print(len(key)) # Check to see if key is of valid length if len(key) == 8 or len(key) == 16 or len(key) == 24: # Clear error label if condition is met error_lbl['text'] = '' # Convert key to bytes key2 = key.encode() key2 = DesKey(key2) # Create DesKey() object using user key # Get user message from entry field encrypted_txt = ent_encrypt.get().encode() # Encrypt user inputted message message = key2.encrypt(encrypted_txt, padding=True) message = str(message) # Trim the byte format from the message message = message[2:] message = message[:len(message) - 1] # Display encrypted sting in encrypted string label encrypted_txt_lbl["text"] = f"Encrypted String: {message}" # Define the Decrypt button decrypt_str_btn = Button(root, text="Decrypt", command=decrypt_txt) # Add Decrypt button to window decrypt_str_btn.grid(row=10, column=0, pady=10) print(message) # If the condition is not met, prompt the user with an error message # asking them to adjust the length of their key else: error_lbl['text'] = 'PLEASE MAKE SURE YOUR KEY IS OF LENGTH 8, ' \ '16, OR 24!'
def handle_request(self, request) -> None: print("Encryption handler running") # Set up encryption key bytes_key = request.key.encode() key0 = DesKey(bytes_key) # Encrypting from direct string if request.data_input: print("Encrypting request from direct string... ...") bytes_str = request.data_input.encode() request.result = key0.encrypt(bytes_str, padding=True) else: print("Encrypting from input file... ...") with open(request.input_file) as file: # bytes_str = request.input_file.encode() bytes_str = file.read().encode() request.result = key0.encrypt(bytes_str, padding=True) if self.next_handler: self.next_handler.handle_request(request) else: return
def as_rep(sock: socket, key_c: DesKey, tgt_path, data_path): data = sock.recv(1024) if b'Error' in data: raise Exception(data.decode('utf-8')[7:]) data = key_c.decrypt(data) data = json.loads(data) # save key with open(data_path, 'w') as jf: json.dump(data, jf) tgt = sock.recv(1024) # save ticket with open(tgt_path, 'wb') as f: f.write(tgt) return data, tgt
def connect(self): global s, key_exchange, pub_key, dh_key, shared_key s.connect(('', 9000)) s.sendall(bytes(str(pub_key), 'utf8')) key_exchange = s.recv(1024) strings = str(key_exchange, 'utf8') num = int(strings) dh_key = (num**priv_key) % q str_temp = "00000" + str(dh_key) print(str_temp) shared_key = DesKey(str_temp.encode('utf-8')) print("sent Pub Key", pub_key) t = threading.Thread(target=self.recieve, args=[s]) t.start()
def handle(self): data = self.request[0].strip() socket = self.request[1] print("{} wrote:".format(self.client_address[0])) print(data) if data == b'TGS_REQ': tgt = socket.recv(1024) ss = socket.recv(1024).decode('utf-8') aut1 = socket.recv(1024) if ss not in services: socket.sendto(b'Error: invalid ss_id', self.client_address) return tgt = K_TGS.decrypt(tgt) c1, key_c_tgs, p1, t_kdc = json.loads(tgt) key_c_tgs = DesKey(key_c_tgs.encode('utf-8')) aut1 = key_c_tgs.decrypt(aut1) aut1 = json.loads(aut1) c2, t_c = aut1 t_c = dt.datetime.fromtimestamp(t_c) t_kdc = dt.datetime.fromtimestamp(t_kdc) delta = (t_c - t_kdc).total_seconds() print(c1, c2, delta, p1) # TGS_REP if c1 == c2 and delta / 3600 < p1: key_c_ss = ''.join( secrets.choice(string.ascii_letters + string.digits) for _ in range(8)) p2 = 10 # hours data_c_tgs = json.dumps([key_c_ss, ss, p2]).encode('utf-8') data_c_tgs = key_c_tgs.encrypt(data_c_tgs) socket.sendto(data_c_tgs, self.client_address) t3 = int(dt.datetime.utcnow().timestamp()) tgs = json.dumps([c1, ss, t3, p2, key_c_ss]).encode('utf-8') tgs = K_SS.encrypt(tgs) socket.sendto(tgs, self.client_address) else: socket.sendto(b'Error: Unauthorized', self.client_address)
def handle_request(self, request: Request): """ handles decryption depending on the type of input source. :param request: Request :return: self.next_handler """ print("Decryption handler running...") byte_key = request.key.encode() key = DesKey(byte_key) if request.data_input: print("Decrypting from the string passed...") request.result = ast.literal_eval(request.data_input) else: with open(request.input_file, "rb+") as file: request.result = file.read() request.result = key.decrypt(request.result, padding=True).decode('utf-8') if not self.next_handler: return else: self.next_handler.handle_request(request)
def DESBlackbox( ): # Code that generates the plaintext, ciphertext for our attack the inner workings of this code would be hidden in a real scenario, we will treat this as blackbox firstK = DesKey( BitArray(formatKey(BitArray(hex="aaaaaaaa0001b1").bin)).tobytes()) secondK = DesKey( BitArray(formatKey(BitArray(hex="aaaaaaaa001a1a").bin)).tobytes()) p1 = "0123456789ABCDEF" p2 = "A01B23C45D67E89F" c1 = secondK.encrypt(firstK.encrypt(p1)) c2 = secondK.encrypt(firstK.encrypt(p2)) plaincipher.append((p1, c1)) plaincipher.append((p2, c2))
def verify(k1, k2): p, c = plaincipher[1] print("Verify Keys using second plaintext Ciphertext pair") print("Plaintext 2 = " + p) print("Ciphertext 2 =" + c) key1 = DesKey(BitArray(formatKey(k1.bin)).tobytes()) key2 = DesKey(BitArray(formatKey(k2.bin)).tobytes()) c1 = key2.encrypt(key1.encrypt(p)) if (c1 == c): print("Verified key pair using second plaintext ciphertext pair :") print(k1 + "\n") print(k2 + "\n") return True else: return False
def decrypt(masterpass, userid, cipher): # masterpass = hashlib.shake_256(masterkey.encode()) userpass = hashlib.shake_256(userid.encode()) masterpass = masterpass.hexdigest(24) userpass = userpass.hexdigest(24) masterpass = bytearray.fromhex(masterpass) userpass = bytearray.fromhex(userpass) masterpass = DesKey(masterpass) userpass = DesKey(userpass) cipher1 = bytes.fromhex(cipher) plain = masterpass.decrypt(cipher1, padding=True) plain = userpass.decrypt(plain, padding=True) plain = masterpass.decrypt(plain, padding=True) return plain.decode()
def main(): """ Crypt&Decrypt message using DES """ message = input("Podaj wiadomość: ") message = bytes(message, encoding='utf-8') key = input("Podaj klucz: \n") key = fill_to_block(key, 8) key = key.encode('utf-8') key = DesKey(key) starttime = timeit.default_timer() encrypted_message = encrypt_by_des(message, key) print("Czas szyfrowania używając DES: ", timeit.default_timer() - starttime, "s") starttime = timeit.default_timer() decrypted_message = decrypt_des(encrypted_message, key) print("Czas odszyfrowania DES: ", timeit.default_timer() - starttime, "s") print("Zaszyfrowany tekst: ", encrypted_message) print("Odszyfrowany tekst: ", decrypted_message.decode("ISO-8859-1").rstrip('\0'))
def encrypt(masterpass, userid, plain): # masterpass = hashlib.shake_256(masterkey.encode()) userpass = hashlib.shake_256(userid.encode()) masterpass = masterpass.hexdigest(24) userpass = userpass.hexdigest(24) masterpass = bytearray.fromhex(masterpass) userpass = bytearray.fromhex(userpass) masterpass = DesKey(masterpass) userpass = DesKey(userpass) cipher = masterpass.encrypt(bytes(plain, 'utf-8'), padding=True) cipher = userpass.encrypt(cipher, padding=True) cipher = masterpass.encrypt(cipher, padding=True) cipher1 = '' for i in cipher: cipher1 = cipher1 + format(i, '02x') return cipher1
def brute_force_des(key_size): # Generating random key of 'key_size' bits in bytes format key = randint(2**(key_size - 1), 2**key_size - 1).to_bytes(8, byteorder='big') des = DesKey(key) # Chosen text pair plain_text = b"Hello World!" cypher_text = des.encrypt(plain_text, padding=True) # Redundant Check # deciphered_text = des.decrypt(cypher_text, padding=True) # Calculating Time of brute-force attack start = time() # Iterating on all possible space of keys for i in range(2**key_size): des = DesKey(i.to_bytes(8, byteorder='big')) decrypted_text = des.decrypt(cypher_text, padding=True) if decrypted_text == plain_text: # print(i.to_bytes(8, byteorder='big'), decrypted_text, sep = '\n', end = '\n\n') # print(key, des, plain_text, cypher_text, deciphered_text, des.is_single(), sep='\n', end = '\n\n') return time() - start
def des3(): mode = input("Input mode - e or d: ") key0 = input("Input a key with length 24: \n") keys = seperateKey(key0) key1 = DesKey(keys[0].encode()) key2 = DesKey(keys[1].encode()) key3 = DesKey(keys[2].encode()) if(mode=="e"): data = input("Input data: \n") s1 = key1.encrypt(data.encode(), padding=True) s2 = key2.decrypt(s1, padding=True) s3 = key3.encrypt(s2, padding=True) f = open("ciphertext", "wb") f.write(s3) print("Encryption done") elif(mode=="d"): filename = input("ciphertext filename: ") f = open(filename, "rb") lines = f.readlines() s3 = key3.decrypt(lines[0], padding=True) s2 = key2.encrypt(s3, padding=True) s1 = key1.decrypt(s2, padding=True) print(s1) else: print("Mode not supported")
def generateDesKey(seedString): bString = bytes(seedString) key = DesKey(bString) return key
#!/usr/bin/python from des import DesKey key0 = DesKey("hsueo se") # FOR DES key1 = DesKey( "a key for TRIPLE") # for 3DES, same as "a key for TRIPLEa key for" key2 = DesKey("a 24-byte key for TRIPLE") # for 3DES key3 = DesKey("12345678REAL_KEY") # for DES, same as "REAL_KEY" key0.is_single() key1.is_triple() key2.is_single() key3.is_triple() enc = key0.encrypt("any long message") print enc