Exemple #1
0
def validate_ticket(data):
    data_dict = json.loads(data)
    ticket = DES.decrypt(IOTKEY[:8], base64.b64decode(data_dict["ticket"]))
    ticket_dict = json.loads(ticket)
    try:
        sessionkey = base64.b64decode(ticket_dict["sessionkey"])
        authenticator = json.loads(
            DES.decrypt(sessionkey[16:24],
                        base64.b64decode(data_dict["authenticator"])).decode())
    except:
        return None
    timestamp = datetime.strptime(authenticator["timestamp"],
                                  '%Y-%m-%d %H:%M:%S.%f')
    lifetime = datetime.strptime(ticket_dict["lifetime"],
                                 '%Y-%m-%d %H:%M:%S.%f')
    if authenticator["logout"] == "True":
        authenticator_set.clear()
        print("authenticator_list:\n", authenticator_set)
        return "Successfully logged out from IoT.", "logout"
    if datetime.now() > lifetime:
        authenticator_set.clear()
        return "expired"
    if authenticator["username"] != ticket_dict["username"]:
        return None
    if data_dict["server"] != ticket_dict["server"]:
        return None
    if (authenticator["username"], timestamp) in authenticator_set:
        return None
    authenticator_set.add((authenticator["username"], timestamp))
    print("authenticator_list:\n", authenticator_set)
    return data_dict["command"]
def tgs_server(auth):
    info = {
        'tgt':
        auth['tgt'],
        'auth':
        DES.encrypt(
            str({
                'c': __client,
                'time': datetime.datetime.now().timestamp()
            }), auth['key']),
        'id':
        __target
    }

    print('\n\tRequest to TGS_server:')
    print(info)

    res_encr = TGS_server(info)

    print('\n\tTGS_server encrypted response:')
    print(res_encr)

    res = DES.decrypt(res_encr, auth['key'])

    print('\n\tTGS_server decrypted response:')
    print(res)

    return eval(res)
    def getResults(self, key, rounds, data, array):
        """
        Iterate through many random permutations of
        masking and conduct DES for certain number of rounds
        Adds to list of results if similar.
        """

        counter_without_result = 0
        results = {}
        while True:

            if counter_without_result > 2**17:
                break

            curr_len = len(results)

            num1, num2 = self._get_xor_hex(array, results)
            hex_value = num1 + num2

            new_data = self.bitwise_xor(data, hex_value)
            des_ = DES(key, new_data, self.rounds, self.mode)

            new_rounds = des_._encrypt()

            results = self.check_similarity(results, rounds, new_rounds,
                                            hex_value)

            if len(results) > curr_len:

                counter_without_result = 0
            else:
                counter_without_result += 1

        return results
def ss_server(tgs_ans):
    time = datetime.datetime.now().timestamp()
    info = {
        'tgs': tgs_ans['tgs'],
        'auth': DES.encrypt(str({
            'c': __client,
            'time': time
        }), tgs_ans['key'])
    }

    print('\n\tRequest to SS_server:')
    print(info)

    res_encr = SS_server(info)

    print('\n\tSS_server encrypted response:')
    print(res_encr)
    res = eval(DES.decrypt(res_encr, tgs_ans['key']))

    print('\n\tSS_server decrypted response:')
    print(res)

    if abs(res - time - 1) > 1e-6:
        raise ValueError("Not connected")

    print('\n\nOK. Connected')
Exemple #5
0
def TGS_server(info: dict):
    tgt_encr = info['tgt']
    auth_encr = info['auth']
    service_id = info['id']

    tgt = DES.decrypt(tgt_encr, database.K_as_tgs)
    tgt = eval(tgt)
    k_c_tgs = tgt['key']

    auth = DES.decrypt(auth_encr, tgt['key'])
    auth = eval(auth)

    if auth['c'] != tgt['c']:
        raise ValueError('client id not equal')

    if auth['time'] - tgt['time'] > tgt['period']:
        raise ValueError('ticket is not valid')

    k_tgs_ss = database.keys[(service_id, database.tgs_id)]
    k_c_ss = database.keys[tuple(sorted((service_id, auth['c'])))]

    tgs = {
        'c': auth['c'],
        'ss': service_id,
        'time': datetime.now().timestamp(),
        'period': 1000,
        'key': k_c_ss
    }

    res = {
        'tgs': DES.encrypt(str(tgs), k_tgs_ss),
        'key': k_c_ss
    }

    return DES.encrypt(str(res), k_c_tgs)
def generate_session(username, password, servername, network_address):
    global i
    i += 1
    key = hash.generate_session()  # key for the session
    dateTimeObj = datetime.now()  # gets the current timestamp
    timestampStr = dateTimeObj.strftime(
        "%Y-%m-%d %H:%M:%S.%f")  # converts the timestamp to a readable format
    life = str(dateTimeObj +
               timedelta(hours=1))  # lifetime for the generated ticket

    print(i, timestampStr)

    # Create the ticket with correct parameters and encrypt it using DES
    ticket = '{{"username":"******","server":"{}","network":"{}","sessionkey":"{}","timestamp":"{}","lifetime":"{}"}}'.format(
        username, servername, network_address, key, timestampStr, life)
    print(i, ticket)
    eTicket = DES.encrypt(IOTKEY[:8], ticket)
    eticket_str = base64.b64encode(eTicket).decode("utf-8")
    payload = '{{"sessionkey":"{}","timestamp":"{}","lifetime":"{}","ticket":"{}"}}'.format(
        key, timestampStr, life, eticket_str)

    # # Encrypt the client's key using DES
    client_key = base64.b64decode(password)
    cipher = DES.encrypt(client_key[48:56], payload)

    # Add a salt to the password hash and return the packet
    salt = base64.b64encode(client_key[:32]).decode("utf-8")
    return_packet = '{{"salt":"{}","payload":"{}"}}'.format(
        salt,
        base64.b64encode(cipher).decode("utf-8"))
    return return_packet.encode()
Exemple #7
0
def Des(str, key, mode):
    if mode == 0:  #加密
        text = str
        length = len(text)
        if length % 4 > 0:
            text = text + (4 - (length % 4)) * " "
            length = len(text)
        finalRes = ""
        for i in range(int(length / 4)):
            tempText = [text[j] for j in range(i * 4, i * 4 + 4)]
            finalRes = finalRes + DES.Des(tempText, key)
        #print(finalRes)
        return finalRes

    elif mode == 1:  #解密
        text = str
        length = len(text)
        finalRes = ""
        for i in range(int(length / 16)):
            tempText = text[i * 16:i * 16 + 16]
            finalRes = finalRes + DES.DeDes(tempText, key)
        #print(finalRes)
        return finalRes
    else:  #错误调用
        return None
Exemple #8
0
def encrypt(file, save_as, schema, base_path):

    if schema == 'AES':
        pickle_in = open(base_path + 'en-de/aes.p', 'rb')
        passwd = pickle.load(pickle_in)
        pickle_in.close()
        AES.encrypt_AES(file, passwd, save_as)

    elif schema == 'RSA':

        RSA.encrypt_RSA(file, save_as, base_path)

    elif schema == 'DES':
        pickle_in = open(base_path + 'en-de/des.p', 'rb')
        passwd = pickle.load(pickle_in)
        pickle_in.close()
        DES.encrypt_DES(file, passwd, save_as)
    elif schema == 'BF':
        pickle_in = open(base_path + 'en-de/bf.p', 'rb')
        #print(base_path)
        passwd = pickle.load(pickle_in)
        pickle_in.close()
        bf.encrypt_bf(file, passwd, save_as)

    else:
        print('pending')
        sys.exit(2)
Exemple #9
0
def generate_session(username, password, servername, network_address):
    global i
    i += 1
    key = hash.generate_session()
    dateTimeObj = datetime.now()
    timestampStr = dateTimeObj.strftime("%Y-%m-%d %H:%M:%S.%f")
    life = str(dateTimeObj + timedelta(hours=1))

    print(i, timestampStr)

    ticket = '{{"username":"******","server":"{}","network":"{}","sessionkey":"{}","timestamp":"{}","lifetime":"{}"}}'.format(
        username, servername, network_address, key, timestampStr, life)
    print(i, ticket)
    eTicket = DES.encrypt(IOTKEY[:8], ticket)
    eticket_str = base64.b64encode(eTicket).decode("utf-8")
    payload = '{{"sessionkey":"{}","timestamp":"{}","lifetime":"{}","ticket":"{}"}}'.format(
        key, timestampStr, life, eticket_str)

    client_key = base64.b64decode(password)
    cipher = DES.encrypt(client_key[48:56], payload)

    salt = base64.b64encode(client_key[:32]).decode("utf-8")
    return_packet = '{{"salt":"{}","payload":"{}"}}'.format(
        salt,
        base64.b64encode(cipher).decode("utf-8"))
    return return_packet.encode()
Exemple #10
0
def main():
    des = DES()
    Des_IV = "Passw0rd"
    encode = des.encrypt("Passw0rd", Des_IV, str("Hello World!"))
    encode2 = des.decrypt("Passw0rd", Des_IV,
                          str("53c8927a4dd1e9b6f44c9d53af92c794"))
    print(encode)

    print(encode2)
Exemple #11
0
def test_transformation():
    #round1
    rd = 1
    c = '1111000011001100101010100000'
    d = '1010101011001100111100000000'
    expect = '000010110000001001100111100110110100100110100101'
    result, c1, d1 = DES.transformation(PC2_table, rd, 'left', c, d)
    assert expect == result, 'transformation PC2 failed'
    assert DES.rotate(rd, c) == c1, 'transformation rotation failed'
    assert DES.rotate(rd, d) == d1, 'transformation rotation failed'
Exemple #12
0
def e_callback():
    checkshortkey()
    try:
        if cipherSelect.get() == 1:
            (fin, fout) = getfiles()
            print(fin, fout)
            DES.DES_encrypt_file(fin, key1.get(), fout)
        if cipherSelect.get() == 2:
            (fin, fout) = getfiles()
            DES.DES3_encrypt_file(fin, key1.get(), key2.get(), key3.get(),
                                  fout)
        if cipherSelect.get() == 3:
            (fin, fout) = getfiles()
            DES.DESX_encrypt_file(fin, key1.get(), key2.get(), key3.get(),
                                  fout)
        if cipherSelect.get() == 4:
            if data_type.get() == 2:
                (fin, fout) = gettxtfiles()
                r = readtxtfile(fin)
                try:
                    k = int(key1.get())
                except ValueError:
                    messagebox.showerror(
                        "Error", "Require integer key for ceasar cipher")
                #add alert
                e = ceasar.ceasar_encrypt(r, k)
                writetxtfile(fout, e)
            else:
                plaintext = T_plaintext.get("1.0", END)
                try:
                    k = int(key1.get())
                except ValueError:
                    messagebox.showerror(
                        "Error", "Require integer key for ceasar cipher")
                #add alert
                e = ceasar.ceasar_encrypt(plaintext, k)
                T_e_text.delete("1.0", END)
                T_e_text.insert("1.0", e)
        if cipherSelect.get() == 5:
            if data_type.get() == 2:
                (fin, fout) = gettxtfiles()
                r = readtxtfile(fin)
                e = playfair.encrypt_playfiar(r, key1.get())
                writetxtfile(fout, e)
            else:
                plaintext = T_plaintext.get("1.0", END)
                #add alert
                e = playfair.encrypt_playfiar(plaintext, key1.get())
                T_e_text.delete("1.0", END)
                T_e_text.insert("1.0", e)
    except:
        messagebox.showerror("Error", "Encryption failed")
    else:
        messagebox.showinfo("Info", "Encryption Successful")
Exemple #13
0
def test_DES_decrypt():
    key = '0123456789ABCDEF'
    cipher = 'e7ab74f51fb2e8a4'
    expect = '789ab123456789aa'
    result = DES.DES_decrypt(cipher, key)
    assert expect == result, 'DES decrypt failed'

    key = '789ABCDEF0123456'
    cipher = '64b8696dfcbdda2f'
    expect = '45ab1a89678923a7'
    result = DES.DES_decrypt(cipher, key)
    assert expect == result, 'DES encrypt failed'
Exemple #14
0
def check(l,message,cipher):
	l1=[]
	print(cipher)
	print(len(message))
	print(len(cipher))
	for a,b in l:
		m1=des.DES(message,a,"Dec")
		m2=des.DES(m1,b,"Dec")
		print(m2)
		if m2 ==cipher:
			l1.append((a,b)) 
	return l1
Exemple #15
0
def test_DES_encrypt():
    key = '0123456789ABCDEF'
    msg = '789AB123456789AA'
    expect = 'e7ab74f51fb2e8a4'
    result = DES.DES_encrypt(msg, key)
    assert expect == result, 'DES encrypt failed'

    key = '789ABCDEF0123456'
    msg = '45AB1A89678923A7'
    expect = '64b8696dfcbdda2f'
    result = DES.DES_encrypt(msg, key)
    assert expect == result, 'DES encrypt failed'
Exemple #16
0
def GenData():
    DES.KeyProNGen()
    one_time_key = DES.info['key']
    print('One time key is : ' + one_time_key + '\n')
    f = open('data.txt', 'w')
    for PT in PlainTextList:
        DES.info['PlainText'] = PT
        f.write(PT)
        f.write("\n")
        DES.Encrypt()
        f.write(DES.info['CipherText'])
        f.write("\n")
    f.close()
Exemple #17
0
    def RuntimeTest(self):
        data = self.testData.strip().split('\n')
        for i in range(len(data)):

            start = time()

            des = DES()
            key = '0001001100110100010101110111100110011011101111001101111111110001'
            des.SetKey(key)
            des.EncryptKey()
            des.SetInputText(data[i])
            des.SetCipherText(des.Encrypt())
            desResult = des.Decrypt()

            stop = time()
            self.runtime += ('DES runtime:' + str(stop - start) + "s\n")

            start = time()

            rsa = RSA()
            rsa.KeyGeneration(128)
            rsaResult = rsa.Decryption(
                rsa.Encryption(int(data[i]), rsa.keyPublic, rsa.n),
                rsa.keyPrivate, rsa.n)

            stop = time()
            self.runtime += ('RSA runtime:' + str(stop - start) + "s\n\n")

        return self.runtime
Exemple #18
0
def main():
    TCP_IP = '127.0.0.1'
    SERV_PORT = 5005
    BOB_PORT = 5004
    ALICE_PORT = 5003
    BUFFER_SIZE = 4096

    #connect to KDC to establish aliceKey
    servSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    servSock.connect((TCP_IP, SERV_PORT))
    #clients are aware of each others' usernames
    alice = "Alice"
    bob = "Bob"
    servSock.send(alice.encode("utf-8"))
    aliceKey = diffieHellman(servSock, False)
    aliceNonce = generate_nonce()
    namePrint(alice, "aliceKey established with server as " + str(aliceKey))

    #connect to Bob to start exchanging information
    bobSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    bobSock.connect((TCP_IP, BOB_PORT))

    #1. Alice sends a request to Bob
    namePrint(alice, "step 1: request to Bob")
    msg = [alice]
    sendMessage(bobSock, msg)

    #3. Alice sends a message to the server identifying herself and Bob, telling the server she wants to communicate with Bob.
    namePrint(alice, "step 3: request to Server")
    encryptedMsg = receiveMessage(bobSock)
    msg = [alice, bob, aliceNonce, encryptedMsg]
    sendMessage(servSock, msg)

    #5. Alice forwards the key to Bob who can decrypt it with the key he shares with the server, thus authenticating the data.
    namePrint(alice, "step 5: pass Server response to Bob")
    encryptedNewMsg = receiveMessage(servSock)
    decryptedServerMsg = DES.frombits(DES.decrypt(encryptedNewMsg, aliceKey))
    serverMsg = decoder.decode(decryptedServerMsg)
    aliceKab = serverMsg[2]
    toBob = serverMsg[3]
    sendMessage(bobSock, toBob)

    #7. Alice performs a simple operation on the nonce, re-encrypts it and sends it back verifying that she is still alive and that she holds the key.
    namePrint(alice, "step 7: send nonce operation result to Bob")
    encryptedNewMsg = receiveMessage(bobSock)
    decryptedBobMsg = DES.frombits(DES.decrypt(encryptedNewMsg, aliceKab))
    decryptedBob = decoder.decode(decryptedBobMsg)
    newMsg = [nonceSubtract(decryptedBob[0])]
    encryptedNewMsg = DES.encrypt(DES.tobits(encoder.encode(newMsg)), aliceKab)
    sendMessage(bobSock, encryptedNewMsg)

    #time too chat!
    namePrint(alice, "Success! Time to chat!")
    threading.Thread(target=chatDataHandler,
                     args=(bobSock, bob, aliceKab)).start()
    while (True):
        sendMessage(
            bobSock,
            DES.encrypt(DES.tobits(encoder.encode(input(""))), aliceKab))
Exemple #19
0
def test_rotate():
    shift_nums = [1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1]
    whole_key = '11110000110011001010101000001010101011001100111100000000'
    left_key = whole_key[:28]
    right_key = whole_key[28:]
    print('left', left_key)
    #round 1 Rotation in encryption (left shift by 1)
    result = DES.rotate(shift_nums[0], left_key)
    expect = '1110000110011001010101000001'
    assert expect == result, 'encryption - round1 rotation failed'

    #round 3 Rotation in encryption(left shift by 2)
    result = DES.rotate(shift_nums[2], left_key)
    expect = '1100001100110010101010000011'
    assert expect == result, 'encryption - round3 rotation failed'
Exemple #20
0
def Test2():
    Message = '\nA very very very very long text message to be encrypted!' * 10
    print('Text Message:  ', Message)
    Key = 'Some Random Secret Key'

    msg = DES.check_msg(Message)
    K = DES.check_key(Key)

    print('Encrypted Text:', end=' ')
    cipher = DES.encryption(K, msg)
    print(cipher)

    print('Decrypted Text:', end=' ')
    Message = DES.decryption(K, cipher)
    print(Message)
Exemple #21
0
def main():
    my_des = DES.Des()
    user_dialog = User_Dialog.UserDialog()

    # encrypt_decrypt = user_dialog.encrypt_or_decrypt()
    message = user_dialog.get_input_message(1)
    key = user_dialog.get_input_key()
    # where_print_result = user_dialog.where_result()

    encrypt_decrypt = user_dialog.DECRYPT
    # message = "D:\Project\Python\des\Messages\Chiffrement_DES_de_Orelsan.txt"
    # key = "D:\Project\Python\des\Messages\Clef_de_Orelsan.txt"
    # message = "je sais pas trop mais je test des trucs plutot interessant ahah"
    # key = "0100110010101110110111001010110111000100011010001100100000101010"
    where_print_result = user_dialog.CONSOLE

    if encrypt_decrypt == user_dialog.ENCRYPT:
        message = my_des.encrypt(message, key)
    elif encrypt_decrypt == user_dialog.DECRYPT:
        message = my_des.decrypt(message, key)

    if where_print_result == user_dialog.CONSOLE:
        print(message)
    elif encrypt_decrypt == user_dialog.FILE:
        open("result.txt", "w").write(message)
        print(
            "Le fichier résultat 'result.txt' a été enregistré à la racine du projet."
        )
Exemple #22
0
def f1(key_in_hex, text_in_bin):
    key = key_in_hex
    hash = MD5.new()
    message = text_in_bin.encode('utf-8')
    hash.update(message)
    hash_md5 = hash.hexdigest()
    ### hash_md5 be like 3c1898a00cc4579728e1268191a64bc6
    hash_bin = bin(int(hash_md5, 16))[2:].zfill(128)
    ### hash_bin be like 00111100000110001001100010100000000011001...., type = str
    first_half = int(hash_bin[:64], 2)
    second_half = int(hash_bin[64:], 2)

    inner_des = DES.encrypt_DES(key, hex(first_half)[2:])  ### hex value
    final_input = int(inner_des, 16) ^ second_half
    result = DES.encrypt_DES(key, hex(final_input)[2:])
    return int(result, 16)
def encryptData(text, private_key, peer_public):
    # des encrypt message
    key = DES.generatekey()
    text = DES.modifytext(text)
    d = DES.des()
    desEndata = d.encrypt(key, text)
    print desEndata
    desEndata = "".join(str(e) for e in desEndata)
    # hash message and signiture
    hashAndSign = RSA.encrypt(md5(text), private_key)
    # encrypted des key and signed message with the other client public_key
    middleData = key + '/' + hashAndSign
    data2 = RSA.encrypt(middleData, peer_public)
    #combine data2 and desEndata
    data = desEndata + '/' + data2
    return data
Exemple #24
0
def Test1():
    # plain text message. 64-bit.
    Msg = '0123456789ABCDEF'
    M = DES.hexToBinary(Msg)

    # Key. 64-bit.
    Key = 'FEDCBA9876543210'
    K = DES.hexToBinary(Key)

    print('Text Message:  ', Msg)
    cipher = DES.DES_Encryption_Decryption(K, M, DES.ENCRYPT)
    print('Encrypted Text:', cipher)

    C = DES.hexToBinary(cipher)
    plain = DES.DES_Encryption_Decryption(K, C, DES.DECRYPT)
    print('Decrypted Text:', plain)
def encrypt():
    print("--------------------加密过程开始--------------------")
    print("--------------------MD5加密开始--------------------")
    mess=input("请输入想加密的消息(默认为hello):") or "hello"
    origin=mess
    md5Tmp=md5.md5hash(mess)
    print(f"明文长度为: {origin.__len__()}\n输入的明文的MD5值为: {md5Tmp}")
    print("--------------------MD5加密结束--------------------\n")
    print("--------------------RSA加密开始--------------------")
    p = int(input("输入RSA密码算法的p值(必须为素数,默认值为47):") or "47")
    q = int(input("输入RSA密码算法的q值(必须为素数且不能与上面的值相同,默认值为463):") or "463")
    ListOut = RSA.generate_key_pair(p,q)
    encrypted = RSA.encrypt(ListOut[0],ListOut[1], md5Tmp)
    encrypted_msg=' '.join(map(lambda x: str(x), encrypted))
    print(f"RSA公钥为: ({ListOut[0]},{ListOut[1]})\nRSA私钥的key值为: {ListOut[2]}\nRSA私钥的n值为: {ListOut[1]}\nRSA密文为:\n{encrypted_msg}\n")
    print("--------------------RSA加密结束--------------------\n")
    print("--------------------DES加密开始--------------------")
    combine=origin+encrypted_msg
    noPairKey=input("输入您的DES密钥(默认值为hello123,必须为8个):") or "hello123"
    desObject=DES.des()
    finalOut=desObject.encrypt(noPairKey,combine,padding=True)
    f=open("encrypted.txt","wb")
    f.write(bytes(finalOut,'utf-8'))
    f.close()
    print(f"DES明文为:\n{combine}\nDES密文为:\n{finalOut}\n密文已编码后写入encrypted.txt文件中")
    print("--------------------DES加密结束--------------------")
    print("--------------------加密过程结束--------------------\n")
Exemple #26
0
def run(messageFile, keyFile):
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.bind((UDP_LOCAL_ADDR, UDP_PORT))

        message = getPayload(fileName=messageFile)

        if len(message) > 250:
            print("Max file size is 250 bytes. Program now exiting.")
            exit()

        key = getKeys(keyFile=keyFile)
        keyRev = reverseKey(key=key)

        encryptedData = DES(keySet=key, data=message)

        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        t = sock.sendto(encryptedData, (UDP_IP_Server, UDP_PORT_SERVER))

        dataTemp = post(sock=sock)
        data = DES(keySet=keyRev, data=dataTemp)

        if data:
            tempData = data.decode("utf-8")
            if ord(tempData[-1]) == 0:
                tempData = tempData[0:-1]

            trueData = ast.literal_eval(tempData)

            messages = ""

            x = len(trueData)
            if x > 5:
                print("Data Length Wrong. Program Now exiting")
                exit()

            for entry in trueData:
                messages = ("\n{})\n{}".format(x, entry)) + messages
                x -= 1

            print(messages)

    except Exception as e:
        print(
            "Something as comprised the socket connecting or data.\nError: {}\nTraceBack: {}"
            .format(e, traceback.format_exc()))
    def main(self):

        permutations = 2**25
        array = []
        for i in range(permutations):
            if str(bin(i)).count('1') < 4:
                array.append(i)
        print(array[:10])
        num_results = 0

        while True:

            key, data = self.generate()

            des = DES(key, data, self.rounds, self.mode)
            rounds = des._encrypt()

            results = self.getResults(key, rounds, data, array)

            sim_results = self.getXORSimiarlity(results)

            if len(sim_results) != 0:

                with open("S5DESTriples" + data, 'a') \
                        as file_out:

                    for i in range(len(sim_results)):

                        if i % 2 == 0:
                            num_results += 1
                            print("S5DES:" + str(num_results))
                            initial_ = key + "\t" + self.mode + '\t' \
                                       + data[:8] + '\t' + data[8:] + '\t'
                            line_w_tabs = "\t".join(rounds) + '\n'
                            file_out.write(initial_)
                            file_out.write(line_w_tabs)


                        initial_ = key + "\t" + self.mode + '\t' \
                                   + sim_results[i][0][:8] + '\t'\
                                   + sim_results[i][0][8:] + '\t'
                        line_w_tabs = "\t".join(sim_results[i][1]) + '\n'
                        file_out.write(initial_)
                        file_out.write(line_w_tabs)
                        end_time = time.time()
                        self.timearray.append(end_time - self.start)
Exemple #28
0
def mac(m, k):
    #given message and key, create a mac code
    #go through m in 8 bit blocks
    i = 0
    j = 8
    d = m[i:j]
    #encrypt block
    #IV= 0 so there is no need to xor with IV, answer will be the same
    o = DES.encrypt(d, k)
    while j != len(m):
        i = i + 8
        j = j + 8
        #xor previosly encrypted block w plaintext
        d = DES.xor(o, m[i:j])
        #encrypt newly xord block
        o = DES.encrypt(d, k)
    return o
Exemple #29
0
def runEncryption(inputList):
    encryptedBinary = []

    newDES = DES.toyDES()

    for string in inputList:
        encryptedBinary.append( newDES.encryptText(string) )

    return encryptedBinary
Exemple #30
0
def runDecryption(encryptedList):
    decryptedBinary = []

    newDES = DES.toyDES()

    for string in encryptedList:
        decryptedBinary.append( newDES.decryptText(string) )

    return decryptedBinary
Exemple #31
0
import DES
if __name__ == '__main__':
    DES.main()
from DES import *

myDES = DES();

plaintext = '0123456789ABCDEF';
key       = '133457799BBCDFF1';

ciphertext = myDES.encrypt(plaintext, key)
decrypted  = myDES.decrypt(ciphertext,key)

print('##########')
print('key        = ' + key       )
print('ciphertext = ' + ciphertext)
print('plaintext  = ' + plaintext )
print('decrypted  = ' + decrypted )

import DES

def write_to_file(filename, data):
    with open(filename, 'w') as f:
        f.write(data + '\n')

key = DES.gen_bits(64)
des = DES.DES(key=key)

write_to_file('test/KEY.txt', key)

pt_len_list = [56, 64, 120, 128, 800]

for pt_len in pt_len_list:
    pt = DES.gen_bits(pt_len)
    ct = des.encrypt(pt)
    
    write_to_file('test/PT-%d.txt' % pt_len, pt)
    write_to_file('test/CT-%d.txt' % pt_len, ct)