Ejemplo n.º 1
0
def get_ticket(clid):
    print("\n\n" + "=" * 30 + format("REQUEST TO AS(clid={})").format(clid) +
          "=" * 30)
    if clid not in client_keys:
        print("\nERROR :FAILD TO FOUND CLIENT")
        exit(1)

    clkey = client_keys[clid]
    print("K_c: {}".format(clkey))
    tm = int(time.time())
    print("now: {}".format(tm))
    C_TGS = des.get_random_key()
    print("GENERATE K_c_tgs key: {}".format(C_TGS))
    TGT = pack("QQQQQ", clid, TGS_ID, tm, TICKET_LENGHT, C_TGS)
    print("\npacked TGT(clid, TGS_ID, now, TICKET_LENGHT, C_TGS): {}\n".format(
        TGT))
    TGT_enc = des.encrypt(TGT, AS_TGS)
    print("\nencrypted TGT x K_as_tgs: {}\n".format(TGT_enc))

    responce = bytearray()
    responce.append(len(TGT_enc) // 256)
    responce.append(len(TGT_enc) % 256)
    responce = responce + TGT_enc + pack("Q", C_TGS)
    print("\n Packed responce(TGT_enc, K_c_tgs):  {}\n".format(responce))

    res = des.encrypt(responce, clkey)
    print(
        "\n Encrypted responce([TGT_enc, K_c_tgs] x K_c):  {} \n".format(res))
    print("=" * 60)
    print()
    return res
Ejemplo n.º 2
0
 def handlePassChange(self):
     if self.textPassNew.text() == "":
         QMessageBox.warning(self, 'Error', 'Nowe hasło nie może być puste')
     elif self.textPass.text() == des.decrypt(
     ) and self.textPassNew.text() != "":
         des.encrypt(self.textPassNew.text())
         self.accept()
     else:
         QMessageBox.warning(self, 'Error', 'Niepoprawne hasło')
Ejemplo n.º 3
0
def get_ticket(TGT_enc, AUTH_enc, server_id):
    print("\n\n" + "=" * 30 + format("REQUEST TO TGS") + "=" * 30)
    print("INPUT TGT x K_as_tgs: {}\n".format(TGT_enc))
    print("INPUT AUTH x K_c_tgs: {}\n".format(AUTH_enc))
    print("SERVER_ID: {}".format(server_id))

    TGT = des.decrypt(TGT_enc, AS_TGS)
    print("\ndecrypted TGT: {}\n".format(TGT))
    clid, tgs_id, tm1, ticket_length, C_TGS = unpack("QQQQQ", TGT)

    print("UNPACK")
    print("Client ID: ", clid)
    print("tgs_id: ", tgs_id)
    print("ticket time: ", tm1)
    print("ticket time length: ", ticket_length)
    print("K_c_tgs: ", C_TGS)

    if server_id not in server_keys:
        print("ERROR: INVALID SERVER")
        exit(1)

    now = int(time.time())
    if now - tm1 > ticket_length or tgs_id != TGS_ID:
        print("ERROR: INVALID TIME")
        exit(1)

    AUTH = des.decrypt(AUTH_enc, C_TGS)
    clid2, tm2 = unpack("QQ", AUTH)

    if now - tm2 > ticket_length or clid != clid2:
        print("ERROR: INVALID TIME")
        exit(1)

    K_c_ss = des.get_random_key()
    print("GEnerated K_c_ss: ", K_c_ss)

    TGS = pack("QQQQQ", clid, server_id, now, SERVER_TICKET_LENGHT, K_c_ss)
    print("\npacked TGS: \n", TGS)
    TGS_enc = des.encrypt(TGS, server_keys[server_id])
    print("\nEncrypted TGS: \n", TGS_enc)

    responce = bytearray()
    responce.append(len(TGS_enc) // 256)
    responce.append(len(TGS_enc) % 256)
    responce = responce + TGS_enc + pack("Q", K_c_ss)

    print("\nPacked responce( TGS x K_ss_tgs, K_c_ss): \n", responce)

    res = des.encrypt(responce, C_TGS)
    print("\nResponce x K_c_tgs: \n", res)
    print("=" * 60)
    print()
    return res
    def test_meet_in_the_middle(self):
        bits = 8
        key1 = des.nth_key(randint(0, 2**bits))
        key2 = des.nth_key(randint(0, 2**bits))

        pairs = []
        for i in range(3):
            plain_text = bytes((randint(0, 255) for i in range(8)))
            cipher_text = des.encrypt(key2, des.encrypt(key1, plain_text))
            pairs.append((plain_text, cipher_text))

        self.assertEqual(des.meet_in_the_middle(bits, pairs), (key1, key2))
Ejemplo n.º 5
0
    def get_ticket(self, client_id):
        print(f'KDC(AS): Request from client with id={client_id}')
        print(f'KDC(AS): Received client id={client_id}', end='\n\n')

        if client_id not in self._client_keys:
            raise AuthorizationError(f'Client is not registered')

        tm = int(time.time())
        k_c_tgs = des.get_random_key()
        tgt = struct.pack("QQQQQ", client_id, self._tgs_id, tm, self._ticket_len, k_c_tgs)
        tgt = des.encrypt(tgt, self._as_tgs)

        response = bytearray(tgt + struct.pack("Q", k_c_tgs))
        response = des.encrypt(response, self._client_keys[client_id])
        return response
Ejemplo n.º 6
0
    def start_session(self, packet):
        tgs, aut = packet
        print(
            f'Server id={self.id}: From client received tgs={tgs} and aut={aut}',
            end='\n\n')

        tgs = des.decrypt(tgs, self._key)
        client_id, server_id, ticket_time, server_ticket_length, k_c_ss = struct.unpack(
            "QQQQQ", tgs)

        now = int(time.time())
        if server_id != self._id:
            AuthenticationError('Client failed authentication')

        if now - ticket_time > server_ticket_length:
            raise TimeLimitError('Time of ticket is over')

        aut = des.decrypt(aut, k_c_ss)
        copy_client_id, tm2 = struct.unpack("QQ", aut)

        if client_id != copy_client_id:
            AuthenticationError('Client failed authentication')

        if now - tm2 > server_ticket_length:
            raise TimeLimitError('Time of ticket is over')

        response = struct.pack("Q", tm2 + 1)
        response = des.encrypt(response, k_c_ss)
        return response
Ejemplo n.º 7
0
def _encrypt_trace(k, trace, distance):
    """
    加密轨迹
    :param k: 初始密钥
    :param trace: 轨迹
    :param distance: 距离
    :return:
    """
    # 对 k 值进行 base64 解码
    text = base64.b64decode(k)
    # 对解码后的 k 值进行 DES 解密(密钥: sshummei), 取前8位作为下一次加密的密钥
    new_key = decrypt('sshummei', text)[:8]
    # 构造待加密数据
    data = {
        # 滑动距离 / 400
        "d": distance / 400,
        # 轨迹
        "m": trace,
        # 滑动所用时间
        "c": trace[-1][-1],
        # 验证码图片尺寸, 宽
        "w": 400,
        # 验证码图片尺寸, 高
        'h': 200,
        # 设备
        'os': 'web_pc',
        # 是否 webdriver
        "cs": 0,
        "wd": 0,
        'sm': -1
    }
    # 最后加密 DES
    return new_key, encrypt(new_key,
                            json.dumps(data).replace(' ', '')).decode()
Ejemplo n.º 8
0
 def testOnlyNumbers(self):
     key = []
     for _ in range(8):
         key.append(random.randint(0, 255))
     plaintext = "1 231 3123 111"
     ciphertext = encrypt(key, plaintext)
     print(helper.byte_to_str(ciphertext))
     self.assertTrue(decrypt(key, ciphertext) == plaintext)
Ejemplo n.º 9
0
 def testBasicEN_RANDKEY(self):
     key = []
     for _ in range(8):
         key.append(random.randint(0, 255))
     plaintext = "Python is an interpreted, high-level, general-purpose programming language. " \
                 "It was created by Guido van Rossum and first released in 1991."
     ciphertext = encrypt(key, plaintext)
     self.assertTrue(decrypt(key, ciphertext) == plaintext)
Ejemplo n.º 10
0
    def connect(self, server):
        print(
            f'Client id={self._id}: Try to connect to server with id={server.id}',
            end='\n\n')

        try:
            response = self._kdc.get_tgt((self._id, ))
            print(
                f'Client id={self._id}: From KDC(AC) received tgt and c_tgs: {response}',
                end='\n\n')
            response = des.decrypt(response, self._key)
            tgt = response[:-8]
            c_tgs, = struct.unpack("Q", response[-8:])

            now = int(time.time())
            aut = struct.pack("QQ", self._id, now)
            aut = des.encrypt(aut, c_tgs)

            response = self._kdc.get_tgs((tgt, aut, server.id))
            print(
                f'Client id={self._id}: From KDC(TGS) received tgs and k_c_ss: {response}',
                end='\n\n')
            response = des.decrypt(response, c_tgs)
            tgs = response[:-8]
            k_c_ss, = struct.unpack("Q", response[-8:])

            now = int(time.time())
            aut = struct.pack("QQ", self._id, now)
            aut = des.encrypt(aut, k_c_ss)

            response = server.start_session((tgs, aut))
            print(
                f'Client id={self._id}: From server received increment time: {response}',
                end='\n\n')
            response = des.decrypt(response, k_c_ss)
            inc_time, = struct.unpack("Q", response)

            if inc_time != now + 1:
                raise AuthenticationError('Server failed authentication')

            print(
                f'Client id={self._id}: Success connect to server with id={server.id}'
            )

        except Exception as e:
            print(e)
Ejemplo n.º 11
0
def main():
    key = input()
    msg = input()
    count = int(input())

    for _ in range(count):
        msg = des.encrypt(msg, key)

    print(msg)
Ejemplo n.º 12
0
def req(command_id, data):
    baseRequestBody["head"]["command_id"] = command_id
    baseRequestBody["data"] = data
    res = session.post(url=gatewayUrl,
                       data={
                           "string":
                           encrypt(json.dumps(baseRequestBody)).decode(),
                           "app_version": "2.19"
                       }).text.strip().replace(" ", "")
    return json.loads(decrypt(res).decode())
Ejemplo n.º 13
0
 def send_test_message(self, session_key):
     # generate a test message
     test_message = generate_rand(32)
     
     # encrypt the message and make it a string
     encrypted_message = encrypt(test_message, session_key)
     encrypted_message = otos(encrypted_message, 32)
     
     self.other_user_connection.send_message(encrypted_message)
     
     return test_message
    def test_nth_key(self):
        self.assertEqual(des.nth_key(765637), unhexlify('01010101015dba8a'))
        self.assertEqual(des.encrypt(des.nth_key(1),
                                     unhexlify('0102030405060708')),
                         unhexlify('6613fc98d6d2f56b'))

        for j in range(1000):
            key = des.nth_key(randint(0, 10000000))
            for i in range(8):
                # Assert hamming weight odd for each byte
                self.assertEqual(bin(key[i]).count('1') % 2, 1)
Ejemplo n.º 15
0
def sanityCheck2():
    """Tests multi-block DES encryption and decryption"""
    try:
        key = [0x0f, 0x15, 0x71, 0xc9, 0x47, 0xd9, 0xe8, 0x59]
        plaintext = "The quick brown fox jumps over the lazy dog cat"
        ciphertext = encrypt(key, plaintext)
        print(ciphertext)
        assert decrypt(key, ciphertext) == plaintext
    except AssertionError:
        return False
    return True
Ejemplo n.º 16
0
def sanityCheck2():
    try:
        key = [0x0f, 0x15, 0x71, 0xc9, 0x47, 0xd9, 0xe8, 0x59]
        plaintext = "moia zizn prenadlezit arde"
        ciphertext = encrypt(key, plaintext)
        assert decrypt(key, ciphertext) == plaintext
        print(plaintext)
        print(ciphertext)
    except AssertionError:
        return False
    return True
Ejemplo n.º 17
0
    def get_ticket(self, tgt, aut, server_id):
        tgt = des.decrypt(tgt, self._as_tgs)
        client_id, tgs_id, tm1, ticket_length, c_tgs = struct.unpack(
            "QQQQQ", tgt)
        print(f'KDC(TGS): Request from client with id={client_id}')
        print(
            f'KDC(TGS): Received tgt={tgt}, aut={aut}, server id={server_id}',
            end='\n\n')

        if server_id not in self._server_keys:
            raise AuthorizationError(
                f'Server with id={server_id} is not registered')

        now = int(time.time())
        if now - tm1 > ticket_length:
            raise TimeLimitError('Time of ticket is over')

        if tgs_id != self._id:
            raise AuthenticationError('TGS ids are not equal')

        aut = des.decrypt(aut, c_tgs)
        copy_client_id, tm2 = struct.unpack("QQ", aut)

        if now - tm2 > ticket_length:
            raise TimeLimitError('Time of ticket is over')

        if client_id != copy_client_id:
            raise AuthenticationError('Client ids are not equal')

        k_c_ss = des.get_random_key()

        tgs = struct.pack("QQQQQ", client_id, server_id, now, self._ticket_len,
                          k_c_ss)
        tgs = des.encrypt(tgs, self._server_keys[server_id])

        response = bytearray(tgs + struct.pack("Q", k_c_ss))
        response = des.encrypt(response, c_tgs)
        return response
 def diffie_hellman_response(self):
     message = self.kdc_connection.get_message()
     if message != '':
         p = stoo(message[:512])
         g = stoo(message[512:1024])
         B = stoo(message[1024:])
         a = random.randint(3, p - 2)
         A = pow(g, a, p)
         s = pow(B, a, p)
         s %= (1 << 10)  # only need last 10 bits for DES encrypt
         encrypted_key = encrypt(self._key, s)
         message = otos(A, 512) + otos(encrypted_key, 2)
         self.kdc_connection.send_message(message)
         return True
Ejemplo n.º 19
0
def encrypt(text, keys):
    for key in keys:
        enc = []
        des_key = des.get_keys(key)
        for block in rw.big_text_to_bin(text):
            encrypted_block = des.encrypt(block, des_key)
            enc.extend(encrypted_block)

        text = []
        for i in xrange(len(enc) / 8):
            text.append(rw.from_bin(enc[i * 8:(i + 1) * 8]))

        text = ''.join(text)

    return text
    def respond_to_test_message(self, session_key):
        message = self.other_user_connection.get_message()
        if message != '':
            # decrypt message
            decrypted_message = otos(decrypt(stoo(message), session_key))

            # use the confirmation function
            hashed_message = User.confirm(decrypted_message)

            # encrypt hashed result
            encrypted_message = otos(encrypt(stoo(hashed_message),
                                             session_key))

            # send the encrypted message to bob
            self.other_user_connection.send_message(encrypted_message)

            return True
Ejemplo n.º 21
0
def request(TGS_enc, AUTH_enc):
    print("=" * 30 + "REQUEST TO SERVER" + "=" * 30)
    print("Input TGS x K_ss_tgs: \n{}\n".format(TGS_enc))
    print("Input AUTH x K_c_ss: \n{}\n".format(AUTH_enc))

    TGS = des.decrypt(TGS_enc, my_key)
    print("TGS: \n{}\n".format(TGS))
    clid, server_id, ticket_time, server_ticket_length, K_c_ss = unpack(
        "QQQQQ", TGS)

    print("UNPACK")
    print("clid: ", clid)
    print("server id: ", server_id)
    print("ticket time: ", ticket_time)
    print("server_ticket_length: ", server_ticket_length)
    print("K_c_ss: ", K_c_ss)

    now = int(time.time())
    if server_id != my_id or now - ticket_time > server_ticket_length:
        print("ERROR")
        exit(1)

    auth = des.decrypt(AUTH_enc, K_c_ss)
    print("AUTH: \n{}\n".format(auth))
    clid2, tm2 = unpack("QQ", auth)

    print("Request client ID: ", clid2)
    print("Request time: ", tm2)

    if clid != clid2 or now - tm2 > server_ticket_length:
        print("ERROR")
        exit(1)

    responce = pack("Q", tm2 + 1)

    print("Responce: \n{}\n".format(responce))
    res = des.encrypt(responce, K_c_ss)
    print("Responce x K_c_ss: \n{}\n".format(res))
    print()
    print("=" * 60)
    print()
    return res
Ejemplo n.º 22
0
def main():
    parser = create_parser()
    args = parser.parse_args(sys.argv[1:])

    output_file_name = args.input_file + ('.dec' if args.decrypt else '.enc')

    input_file = open(args.input_file, 'rb')
    output_file = open(output_file_name, 'wb')

    outputbytes = b''

    if args.decrypt:
        outputbytes = des.decrypt(input_file.read())
    else:
        outputbytes = des.encrypt(input_file.read())

    output_file.write(outputbytes)

    input_file.close()
    output_file.close()
Ejemplo n.º 23
0
def exec_menu(choice):

    if choice == "1":
        key = []
        print("Prosze wprowadzic nazwe pliku z kluczem - kazdy bajt klucza podaj w osobnej linii...")
        key_file_name = input(" >> ")
        print("Prosze wprowadzic nazwe pliku z tekstem...")
        msg_file_name = input(" >> ")
        with open(key_file_name, 'r') as key_file:
            key = [int(line.strip()) for line in key_file]
        with open(msg_file_name, 'r') as msg_file:
            msg = msg_file.read().replace('\n', ' ')
        print("Zaszyfrowany tekst w postaci bajtow zapisano w pliku encrypted.txt.")
        encrypted = encrypt(key, msg)
        with open('encrypted.txt', 'w') as output_file:
            for byte in encrypted:
                output_file.write("%s\n" % byte)
        main_menu()

    if choice == "2":
        key = []
        print("Prosze wprowadzic nazwe pliku z kluczem - kazdy bajt klucza podaj w osobnej linii...")
        key_file_name = input(" >> ")
        print("Prosze wprowadzic nazwe pliku z zaszyfrowanymi bajtami...")
        msg_file_name = input(" >> ")
        with open(key_file_name, 'r') as key_file:
            key = [int(line.strip()) for line in key_file]
        with open(msg_file_name, 'r') as msg_file:
            msg = [int(line.strip()) for line in msg_file]
        print("Odszyfrowany tekst zapisano w pliku decrypted.txt.")
        encrypted = decrypt(key, msg)
        with open('decrypted.txt', 'w') as output_file:
            for byte in encrypted:
                output_file.write("%s" % byte)
        main_menu()

    if choice == "3":
        unit_tests.unittest.main()

    if choice == "0":
        return
Ejemplo n.º 24
0
 def handle(self):
     if not self.proof_of_work():
         return
     # We all know that DES can be bruteforced
     # But it should be longer then 20 minutes?
     signal.alarm(20 * 60)
     key = self.genkey()
     while True:
         self.dosend("plaintext(hex): ")
         pt = self.recvhex(20001)
         if pt == '':
             break
         ct = des.encrypt(pt, key)
         self.dosend("%s\n" % ct.encode('hex'))
     self.dosend("key(hex): ")
     guess = self.recvhex(20)
     if guess == key:
         self.dosend("nyao! %s\n" % FLAG)
     else:
         self.dosend("meow?\n")
     self.request.close()
Ejemplo n.º 25
0
 def sym_encrypt(self, key, msg):
     cipher = 0
     if self.sym_key_alg == "des":
         cipher = des.encrypt(key, msg)
     return cipher
Ejemplo n.º 26
0
 def test_encryption(self):
     plaintext = bytes.fromhex('0123456789ABCDEF')
     key = bytes.fromhex('133457799BBCDFF1')
     ciphertext = bytes.fromhex('85E813540F0AB405')
     
     assert(des.encrypt(plaintext, key) == ciphertext)
Ejemplo n.º 27
0
 def test_wrong_length(self):
     with self.assertRaises(ValueError):
         des.encrypt(b'a', b'b', 'ECB')
Ejemplo n.º 28
0
 def test_numeric_input(self):
     with self.assertRaises(TypeError):
         des.encrypt(1, 2, 'ECB')
Ejemplo n.º 29
0
 def test_pad_single_block_pkcs5(self):
     expected = 'e+qiqfAneQI='
     actual = base64.b64encode(des.encrypt(b'l', KEY, 'ECB')).decode('ascii')
     self.assertEqual(expected, actual)
Ejemplo n.º 30
0
    def test_decrypt_and_unpad_cbc(self):
        LOCAL_STR = b'linus'
        expected = LOCAL_STR
        actual = des.decrypt(des.encrypt(LOCAL_STR, KEY, iv=IV), KEY, iv=IV)

        self.assertEqual(expected, actual)
Ejemplo n.º 31
0
 def test_encrypt(self):
     des_cipher = des.encrypt(self.plain)
     self.assertEqual(des_cipher[:64], self.cipher)
     self.assertEqual(len(des_cipher), 128)
Ejemplo n.º 32
0
 def test_encrypt(self):
     for key, plain, cipher in self._test_vectors:
         self.assertEqual(des.encrypt(key, plain), cipher)
Ejemplo n.º 33
0
 def test_encrypt(self):
     """Test that a message s encrypted via DES."""
     enc = des.encrypt(self.key, 'The message here.')
     s = '3EEB011DC9DF43117BB8DFB26CCB37485EBF13DCEE70A9E1'
     self.assertEquals(enc, s)