def handle_request(self, request_: Request):
     """
     Encrypts either the given string or file
     :param request_: a Request
     :return: a tuple
     """
     print("Encrypting...")
     key = DesKey(request_.key.encode('utf-8'))
     if request_.data_input and request_.input_file:
         return "Choose either a text file or a string to encrypt!!", False
     elif request_.data_input:
         request_.result = key.encrypt(request_.data_input.encode('utf-8'),
                                       padding=True)
         if not self.next_handler:
             return "", True
         return self.next_handler.handle_request(request_)
     elif request_.input_file:
         with open(request_.input_file, 'r') as file:
             data = file.read()
             request_.result = key.encrypt(data.encode('utf-8'),
                                           padding=True)
             if not self.next_handler:
                 return "", True
             return self.next_handler.handle_request(request_)
     else:
         return self.next_handler.handle_request(request_)
Example #2
0
    def handle_request(self, request: Request):
        """
        handles encryption depending on the type of input source.
        :param request: Request
        :return: self.next_handler
        """
        print("Encryption handler running...")
        byte_key = request.key.encode()
        key = DesKey(byte_key)

        if request.data_input:
            print("Encrypting from the string passed...")
            byte_str = request.data_input.encode()
            request.result = key.encrypt(
                byte_str,
                padding=True)  # automatically sets the length to 8, 16 or 24.
        else:
            print("Encrypting from the file...")
            with open(request.input_file) as file:
                byte_str = file.read().encode()
                request.result = key.encrypt(byte_str, padding=True)

        if not self.next_handler:
            return
        else:
            self.next_handler.handle_request(request)
Example #3
0
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")
Example #4
0
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 handle(self, request) -> bool:
     encoding_key = DesKey(bytes(request.key, "utf8"))
     if request.data_input is not None:
         request.result = encoding_key.encrypt(bytes(
             request.data_input, "utf8"),
                                               padding=True)
     elif request.input_file is not None:
         file = open(request.input_file, "r")
         request.result = encoding_key.encrypt(bytes(file.read(), "utf8"),
                                               padding=True)
         file.close()
     if not self.next_handler:
         return True
     return self.next_handler.handle(request)
Example #6
0
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
Example #7
0
class DES:
    def __init__(self, key):

        key = key.to_bytes(24, byteorder='big')
        self.key = key
        self.create_cipher()

    def create_cipher(self):

        # try:
        # 	key2 = DES3.adjust_key_parity(self.key)

        # except ValueError:
        # 	pass
        # self.cipher = DES3.new(key1, DES3.MODE_CFB)
        # print(self.key)
        # key2=pad(self.key,24)
        # print(key2)
        assert (len(self.key) == 24)
        self.key1 = DesKey(self.key)
        # print(self.key1.is_triple())

    def encryption(self, data, file=None):
        if file == None:
            data = data.encode(FORMAT)
        cipher_text = self.key1.encrypt(data, padding=True)
        return cipher_text

    def decryption(self, data, file=None):

        plain_text = self.key1.decrypt(data, padding=True)
        if file == None:
            plain_text = plain_text.decode(FORMAT)
        return plain_text
Example #8
0
def decrypt_txt():
    """
    This function decrypts the text that was previously encrypted by first
    encrypting it again and then calling decrypt() to decrypt and display the
    decrypted text to the decrypt_txt_lb()
    """

    key = ent_choose_key.get()  # Get key from the user
    # Check to see if the key is of valid length
    if len(key) == 8 or len(key) == 16 or len(key) == 24:
        # Clear error label is condition is mer
        error_lbl['text'] = ''
        # Convert the key from a string to a bytes format
        key2 = key.encode()
        # Create DesKey() instance
        key2 = DesKey(key2)
        # Encrypt message
        decrypted_txt = ent_encrypt.get().encode()
        decrypted_txt = key2.encrypt(decrypted_txt, padding=True)
        # Decrypt message
        message = key2.decrypt(decrypted_txt, padding=True)
        message = str(message)
        message = message[2:]
        message = message[:len(message) - 1]
        # Pass the message to the label to display to user
        decrypted_txt_lbl["text"] = f"Decrypted String: {message}"
        print(message)
    else:
        error_lbl['text'] = 'PLEASE MAKE SURE YOUR KEY IS OF LENGTH 8, ' \
                            '16, OR 24!'
Example #9
0
def example():
    send_message("\nFor this quick example of encryption, I'll need you to type a word. Any word!\n")
    send_message("Enter it here: ")
    word_received = c.recv(1024)

    # clean up input with regex
    word_received = re.sub(r'[b\'(.*?)\\r\\n\']', '', str(word_received))

    if word_received == "":
        send_message("Oops! You didn't enter anything, let's try again.\n")
        example()
    else:
        genDESKey()
        f = open("DESkey.txt", "r")
        key_from_file = str.encode(f.read())
        key0 = DesKey(key_from_file)

        word_received = bytes(word_received, 'latin-1')
        encrypted_word = key0.encrypt(word_received, padding=True)

        substring = re.search(r"b'(.*?)'", str(encrypted_word)).group(1)

        send_message("\nYour word, encrypted, looks like this: " + substring + "\n\n")
        sleep(7)
        send_message("Pretty hard to read, right? It was encrypted using a popular algorithm called DES, \n")
        send_message("which stands for \"data encryption standard\".\n\n")
        sleep(7)

        return encrypted_word
Example #10
0
def encryptage(data, key):
    ndata = data.encode('utf-8')
    key = parsekey(key)
    nkey = key.encode('utf-8')
    key0 = DesKey(nkey)
    encrypted_message = key0.encrypt(ndata, padding=True)
    return encrypted_message
Example #11
0
class Encryption:
    def __init__(self, password):
        """
        Выполняет инициализацию шифрования

        :param password: Пароль для защиты
        """
        self._des = DesKey(password.encode('utf8'))

    def encrypt(self, text) -> str:
        """
        Шифрует строку

        :param text: Строка для шифрования
        :return: base64 результат
        """
        return b64encode(self._des.encrypt(text.encode('utf8'),
                                           padding=True)).decode('utf8')

    def decrypt(self, text) -> str:
        """
        Расшифровывает строку

        :param text: Строка для расшифровки
        :return: Результат
        """
        return self._des.decrypt(b64decode(text.encode('utf8')),
                                 padding=True).decode('utf8')
    def confirmkey(self):
        pin2 = self.pin_text.toPlainText()
        pad_text = pad(pin2)
        b = bytes(pad_text, 'utf-8')
        key0 = DesKey(b)
        enteredkey = key0.encrypt(b"teamhellowworld", padding=True)

        #with open("keyenter.bytes","wb") as fp:
        #    fp.write(enteredkey)

        with open("keyenter.bytes", "rb") as fp:
            readkey = fp.read()

        print("pin entered:" + pin2)
        if enteredkey == readkey:
            for file in os.listdir(self.storage_path):
                full_path = os.path.join(self.storage_path, file)
                os.chmod(full_path, S_IWRITE)
            self.info.append("correct password")
            print("Correct password")
            return 1
        else:
            for file in os.listdir(self.storage_path):
                full_path = os.path.join(self.storage_path, file)
                os.chmod(full_path, S_IREAD)
            self.info.append("wrong password")
            print("Wrong password")
            return 0
Example #13
0
class DES:
    def __init__(self, key_size, blocklength):
        if key_size != 64:
            raise InvalidKeyLength("Keylength of DES must be 64 bits!")

        if blocklength % 64 != 0:
            raise InvalidCipherBlockLength(
                "Blocklength of DES should be multiplier of 64")

        self._key = None
        self._blocklength = blocklength

    def set_key(self, key):
        string_key = bits_to_bytes(key)

        self._key = DesKey(string_key)

        if not self._key.is_single():
            raise WrongConfiguration("3DES has been configured")

    def encrypt(self, message):
        byte_message = bits_to_bytes(message)
        encrypted_bytes = None
        for _ in range(round(self._blocklength / 64)):
            encrypted_bytes = self._key.encrypt(byte_message)
        return bytes_to_bits(encrypted_bytes)

    def decrypt(self, message):
        byte_message = bits_to_bytes(message)
        decrypted_bytes = None
        for _ in range(round(self._blocklength / 64)):
            decrypted_bytes = self._key.decrypt(byte_message)

        return bytes_to_bits(decrypted_bytes)
Example #14
0
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 ) ] ) )

		if int( SECRET[ i % len( SECRET ) ] ) == 1:
			enc_block = key.encrypt( enc_block )

		enc_blocks.append( enc_block.encode( 'hex' ) )

	return enc_blocks
Example #15
0
def des_timer(test_vectors):
    """Encrypts (DES) each element of test_vector with a padding (64 bits) 
		and returns a list of tuples with (encryption time, decryption time)"""
    timelist = []
    for vector in test_vectors:  #test_vector elements are of byte type
        #key creation for DES
        iv = secrets.token_bytes(8)
        des_instance = DesKey(secrets.token_bytes(8))
        #print(des_instance.is_single())
        #creating padding instance
        padder = padding.PKCS7(64).padder()
        #encrypting begins (using CBC mode)
        start_e = timer()
        padded_m = padder.update(vector) + padder.finalize(
        )  #padding is included in the process as instructed
        cyphertext = des_instance.encrypt(padded_m, initial=iv)
        end_e = timer()
        #encrypting ends, timing this section
        #print(str(cyphertext))
        #creating unpadding instance
        unpadder = padding.PKCS7(64).unpadder()
        #decrypting begins
        start_d = timer()
        plaintext_d = des_instance.decrypt(cyphertext, initial=iv)
        plaintext = unpadder.update(plaintext_d) + unpadder.finalize()
        end_d = timer()
        #decryption ends
        #print(plaintext)
        timelist.append((end_e - start_e, end_d - start_d))
    return timelist
Example #16
0
def server_program():
    # get the hostname
    host = socket.gethostname()
    port = 12345

    s = socket.socket()
    s.bind((host, port))
    desFile = open("deskey.txt", "r")
    hmacFile = open("hmackey.txt", "r")

    desKeystr = desFile.read()
    desKey = DesKey(desKeystr.encode('utf-8'))

    hmacKey = hmacFile.read()
    hmacKeystr = hmacFile.read()
    byteHmacKey = bytes(hmacKeystr, encoding='utf8')
    digest_maker = hmac.new(byteHmacKey, msg=None, digestmod=hashlib.sha1)

    print("Connecting to client...")

    # configure how many client the server can listen simultaneously
    s.listen(10)
    connection, address = s.accept()  # accepts the new connection
    print("Connection from: " + str(address))
    while True:
        # receive data stream. it won't accept data packet greater than 1024 bytes
        data = connection.recv(1024)

        if not data:
            break
        print("received cipher text: %s" % data.decode('utf-8', 'ignore'))
        pt = desKey.decrypt(data, padding=True).decode()
        print("received plaintext: %s" % pt)
        digest_maker.update(data)
        digest = digest_maker.hexdigest()

        # rhmacKey = hashlib.sha256(str(data).encode('utf-8'))

        print("received HMAC message: " + digest)
        print("calculated HMAC: " + digest)
        print("HMAC Verified")

        print("===========================================================")
        data = input(' -> ')

        ct = desKey.encrypt(data.encode('utf-8'), padding=True)
        digest_maker.update(data.encode())

        print("shared DES key: ", desKeystr)
        print("shared HMAC key: %s" % hmacKey)
        print("sent plaintext: %s" % data)
        print("sent HMAC message: " + digest_maker.hexdigest())
        print("sent ciphertext: %s" % ct.decode('utf-8', 'ignore'))
        print("===========================================================")
        connection.send(ct)
    connection.close()
    desFile.close()
    hmacFile.close()
Example #17
0
    def handle_request(self, request):
        key = DesKey(request.key)  # Create a DesKey object using the user provided key

        if request.encryption_state == CryptoMode.EN:
            request.result = key.encrypt(request.data_input, padding=True)
        else:
            request.result = key.decrypt(request.data_input, padding=True)

        self.next_handler.handle_request(request)  # pass the control to the next handler
Example #18
0
    def handle_request(self, request: Request) -> (str, bool):
        if not request.data_input and request.input_file:
            return self.next_handler.handle_request(request)

        key = DesKey(request.key.encode('utf-8'))
        request.result = key.encrypt(request.data_input.encode('utf-8'),
                                     padding=True)

        if self.next_handler is None:
            return "", True
        return self.next_handler.handle_request(request)
Example #19
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 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 genAndSendCipherText():
    # open read, and encode key, set to key0
    f = open("DESkey.txt", "r")
    key_from_file = str.encode(f.read())
    key0 = DesKey(key_from_file)

    # encrypt plaintext and send to server
    encrypted_message = key0.encrypt(combo_message, padding=True)
    s.send(encrypted_message)

    # print ciphertext to console
    print("sent ciphertext:", end=' ')
    print(encrypted_message)
    print("************************************************")
Example #22
0
 def encrypt_file(self,
                  in_filename,
                  out_filename=None,
                  chunksize=64 * 1024):
     if not out_filename:
         out_filename = in_filename + '.des'
     iv = Generate.generateByteString(self.block_size)
     userkey, index = self.userKey.getEncryptionKey()
     encryptionKey = XORKey(self.key, userkey)
     cipher = DesKey(encryptionKey)
     cipherFunc = lambda x: cipher.encrypt(x, initial=iv)
     UIFunctions.log("DES Encryption Started")
     FileCrypto.encrypt_CBC(index, cipherFunc, iv, self.block_size,
                            in_filename, out_filename, chunksize)
Example #23
0
    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, 'rb') as file_object:
                request.result = key.encrypt(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
Example #24
0
    def handle_request(self, command: Request) -> (bool, str):
        """
        It converts the Key into DesKey and encrypt 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("Encrypting...")
        key = DesKey(command.key.encode("utf-8"))
        command.result = key.encrypt(command.data.encode("utf-8"),
                                     padding=True)
        return self.pass_handler(command)
Example #25
0
 def handle_request(self, request: Request) -> (str, bool):
     """
     Encrypts the data with the key
     :param request: Request from cmd line args
     :return: (str, bool) str: a message, bool True if validation is passed
     """
     data = request.data_input
     if not data:
         return "There is no data to be encrypted.", False
     key = DesKey(request.key.encode('utf-8'))
     request.result = key.encrypt(data, padding=True)
     if self.next_handler:
         return self.next_handler.handle_request(request)
     else:
         return "", True
Example #26
0
def main():
    DESBlackbox()  #generate plaintext ciphertext pairs for some keys
    knownk1 = "aaaaaaaa"  #known 32 bits of keys
    knownkBits = BitArray(hex=knownk1)
    print(knownkBits)
    p, c = plaincipher[0]
    print("Plaintext 1 = " + p)
    print("Ciphertext 1 =" + c)
    for k in generateKeys(knownkBits):
        k1 = formatKey(k.bin)
        key = DesKey(BitArray(k1).tobytes())
        firstDict[key.encrypt(p)] = k
        secondDict[key.decrypt(c)] = k
        mitm()
    mitm()
    def resetkey(self):
        if self.confirmkey():
            with open("keyenter.bytes", "wb") as fp:
                new_pin = self.textEdit_2.toPlainText()
                pad_text = pad(new_pin)
                b = bytes(pad_text, 'utf-8')
                key0 = DesKey(b)
                enteredkey = key0.encrypt(b"teamhellowworld", padding=True)

                print("new pin is:" + new_pin)
                fp.write(enteredkey)
                self.info.append("Reset pin success!")
        else:
            self.info.append("Reset pin fail!")

        return
Example #28
0
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()
Example #29
0
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
Example #30
0
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)