コード例 #1
0
 def receive_loop():
     connect_server()
     while 1:
         cipher = AESCipher(self.serverSharedKey)
         data = cipher.decrypt(self.clientSocket.recv(self.size))
         msg = json.loads(data)
         if msg.struct['message'] == 'Exit Success':
             print 'Connection successfully closed.'
             self.socket.shudown(SHUT_RDWR)
             self.socket.close()
             sys.exit(0)
         elif msg.struct['message'] == 'DH Key Exchange':
             K = str((long(msg.struct['key'])**self.Xc) % shared_prime)
             h = SHA256.new()
             h.update(K)
             K = h.hexdigest()
             sender = msg.struct['sender']
             self.clientRegistry[sender] = {
                 'public_key': msg.struct['key'],
                 'private_key': K
             }
         else:
             sender = msg.struct['sender']
             key = self.clientRegistry[sender]['private_key']
             cipher = AESCipher(key)
             message = cipher.decrypt(msg.struct['message'])
             print message
コード例 #2
0
ファイル: server.py プロジェクト: vonSchmidt/Python-ChatApp
def on_new_client(clientsocket, addr, user):
    while True:  # this while is a listen loop to any client
        msg = clientsocket.recv(size)
        print msg
        # decrypt msg
        cipher = AESCipher(connected_sockets[user]['private_key'])
        msg = cipher.decrypt(msg)
        print addr, ' >> ', msg
        msg = json.loads(msg)
        if msg['messagetype'] == 'command':
            msg['args'].append(msg['sender'])
            response = {
                'messagetype': 'response',
                'response': commands[msg['command']](msg['args'])
            }
            send(response, clientsocket)
            if msg['command'] == '/exit':
                exit()
        elif msg['messagetype'] == 'incoming_connect' or msg[
                'messagetype'] == 'success_connect':
            response = msg
        elif msg['messagetype'] == 'message':
            if msg['receiver'] == '':
                response = {
                    'messagetype': 'send_failed',
                    'messagecontent': 'Could not send: no recipient found.'
                }
            else:
                response = {'messagetype': 'received', 'sender': msg['sender']}
        send(response, clientsocket)
コード例 #3
0
    def loadPasswordList_UI(self):
        self.readPasswords()
        self.ids.remote_password_list.clear_widgets()
        self.ids.local_password_list.clear_widgets()

        self.ids.remote_password_list.add_widget(
            Label(text="Remote Password List"))
        self.ids.local_password_list.add_widget(
            Label(text="Local Password List"))
        cipher = AESCipher("nv93h50sk1zh508v")
        for entry in self.localPasswordList:

            passwordBtn = PasswordButton(text=entry['account'],
                                         background_color=(0.93, 0.93, 0.93,
                                                           1))

            passwordBtn.pw_username = entry['username']
            passwordBtn.pw_account = entry['account']
            try:
                passwordBtn.pw_password = cipher.decrypt(entry['password'])
            except Exception, e:
                print e
                passwordBtn.pw_password = "******"
            passwordBtn.pw_id = entry['id']
            passwordBtn.pw_id = entry['id']

            passwordBtn.pw_location = "Local"

            passwordBtn.bind(on_release=self.onPasswordButtonClick)

            self.ids.local_password_list.add_widget(passwordBtn)
コード例 #4
0
    def process_incoming_message(self, msg_raw, msg_id, owner_str):
        '''
        Process incoming messages
        :param msg_raw: the raw message
        :param msg_id: ID of the message
        :param owner_str: user name of the user who posted the message
        :param user_name: name of the current user
        :param print_all: is the message part of the conversation history?
        :return: None
        '''
        # process message here
        # example is base64 decoding, extend this with any crypto processing of your protocol
        decoded_msg = base64.decodestring(msg_raw)

        group_key = self.group_key

        # last 32 bytes should be the signature
        #encr_msg = decoded_msg
        encr_msg = decoded_msg[:-256]
        signature = decoded_msg[-256:]

        #print signature
        key = RSA.importKey(open(owner_str.lower() + 'PubKey.pem').read())
        h = SHA256.new()
        h.update(encr_msg)
        verifier = PKCS1_PSS.new(key)
        
        if not verifier.verify(h,signature):
            raise Exception('Signature not valid')

        aes_group = AESCipher(group_key)
        # get message key

        # decrypt message using message key
        decoded_msg = aes_group.decrypt(encr_msg)

        # check for correct timestamp
        timestamp = datetime.datetime.strptime(decoded_msg[-27:-1], "%Y-%m-%d %H:%M:%S.%f")
        if self.lastTimeStamp == None:
            if timestamp < datetime.datetime.utcnow():
                self.lastTimeStamp = timestamp
            else:
                raise Exception('Error: timestamp is from a point in the future')
        elif self.lastTimeStamp < timestamp:
            if timestamp < datetime.datetime.utcnow():
                self.lastTimeStamp = timestamp
            else:
                raise Exception('Error: timestamp is from a point in the future')
        else:
            raise Exception('Timestamp is out of order. Possible replay attack.')

        # uncomment to remove timestamp from message
        #decoded_msg = decoded_msg[:-46]

        # print message and add it to the list of printed messages
        self.print_message(
            msg_raw=decoded_msg,
            owner_str=owner_str
        )
コード例 #5
0
ファイル: Server.py プロジェクト: vonSchmidt/Python-ChatApp
 def on_new_client(socket, addr, username):
     while 1:
         msg = socket.recv(size)
         cipher = AESCipher(
             self.serverRegistry.sRegistry[username]['private_key'])
         msg = cipher.decrypt(msg)
         # print addr,' >> ', msg
         msg = json.loads(msg)
         # stuff
     return
コード例 #6
0
ファイル: client.py プロジェクト: vonSchmidt/Python-ChatApp
def receive_loop():
    global recipient, Kc
    while 1:
        cipher = AESCipher(Kc)
        data = cipher.decrypt(s.recv(size))
        msg = json.loads(data)
        print msg
        if msg['response']['messagetype'] == 'success_exit':
            print 'Connection successfully closed.'
            s.shutdown(SHUT_RDWR)
            s.close()
            sys.exit(0)
        elif msg['response']['messagetype'] == 'success_connect':
            Kr = str((long(msg['response']['sharedkey'])**Xc) % shared_prime)
            h = SHA256.new()
            h.update(Kr)
            Kr = h.hexdigest()
            recipient = msg['response']['receiver']
            users_info[recipient] = {
                'public_key': msg['response']['sharedkey'],
                'private_key': Kr
            }
        elif msg['response']['messagetype'] == 'incoming_connect':
            Kr = str((long(msg['response']['sharedkey'])**Xc) % shared_prime)
            h = SHA256.new()
            h.update(Kc)
            Kc = h.hexdigest()
            users_info[msg['response']['sender']] = {
                'public_key': msg['response']['sharedkey'],
                'private_key': Kr
            }
        elif msg['response']['messagetype'] == 'incoming_message':
            receiver = msg['response']['receiver']
            sender = msg['response']['sender']
            cipher = AESCipher(users_info[receiver]['private_key'])
            message = cipher.decrypt(msg['response']['msg'])
            print user, '<', sender + ':', message
        print msg['response']['messagecontent']
コード例 #7
0
ファイル: break.py プロジェクト: dapollak/ctf
def break_next(curr_cipher, condition_function):
    res_chars = ''
    g = itertools.product(CHARS, CHARS)
    while True:
        try:
            curr_chars = ''.join(g.next())
        except StopIteration:
            break

        cipher = AESCipher(hashlib.sha256(curr_chars).digest())

        plain = cipher.decrypt(curr_cipher)
        if condition_function(plain):
            res_chars = curr_chars
            curr_cipher = cipher._unpad(plain)
            break

    return curr_cipher, res_chars
コード例 #8
0
ファイル: break.py プロジェクト: moomoohk/ctf
def break_next(curr_cipher, condition_function):
    res_chars = ''
    g = itertools.product(CHARS, CHARS)
    while True:
        try:
            curr_chars = ''.join(g.next())
        except StopIteration:
            break

        cipher = AESCipher(hashlib.sha256(curr_chars).digest())

        plain = cipher.decrypt(curr_cipher)
        if condition_function(plain):
            res_chars = curr_chars
            curr_cipher = cipher._unpad(plain)
            break

    return curr_cipher, res_chars
コード例 #9
0
    def loadPasswordList_UI(self):
        self.readPasswords()
        self.ids.password_list.clear_widgets()
        cipher = AESCipher("nv93h50sk1zh508v");
        for entry in self.passwordList:

            passwordBtn = PasswordButton(text=entry['account'], background_color=(0.93,0.93,0.93,1))

            passwordBtn.pw_username = entry['username']
            passwordBtn.pw_account=entry['account']
            try:
                passwordBtn.pw_password=cipher.decrypt(entry['password'])
            except Exception, e:
                print e
                passwordBtn.pw_password="******"
            passwordBtn.pw_id=entry['id']

            passwordBtn.bind(on_release=self.onPasswordButtonClick)

            self.ids.password_list.add_widget(passwordBtn)
コード例 #10
0
    def process_message(self, message, client_address):

        print("processing message < " + str(message) + " > from " +
              client_address)

        if message == "":
            return

        elif self.contacts.get(client_address) is None:
            print("Contact has responded to our request!")
            key = self.rsa.decrypt(message)
            self.contacts[client_address] = key

        else:
            print("Received an encrypted message from " + client_address +
                  ": " + str(message))
            key = self.contacts.get(client_address)
            dec = aes.decrypt(key, message)

            print("Decrypted message reads: " + str(message))
            self.controller.display_message(dec, client_address)
コード例 #11
0
    # read ciphertext from input file
    ciphertext = open(input_filename, "r").read()

    # build sha256 hash list for all 2 byte combinations
    hashes, key_map = get_sha256_2bytes()

    # each hash is a possible key, attempt decryption and check padding
    decrypted_data = ''
    current_ciphertext = ciphertext
    layer_keys = []
    guess = []
    for layer in range(4):
        print "decrypting layer %d" % (4 - layer)
        for key in hashes:
            cipher = AESCipher(key)
            decrypted_data = cipher.decrypt(current_ciphertext)
            # for the 3 outermost layers, we can expect the padding to be 16 bytes of 0x10
            # this is because the plaintext for every round (other than the very first) is the
            # ciphertext (multiple of 32 bytes) + iv (16 bytes) combination from the previous round.
            if layer != 3:
                padding_block = decrypted_data[-AES.block_size:]
                is_valid = True
                for ch in padding_block:
                    if ord(ch) != 16:
                        is_valid = False
                        break
                if is_valid:
                    current_ciphertext = AESCipher._unpad(decrypted_data)
                    layer_keys.append(key.encode('hex'))
                    print "solved layer %d with key : %s, padding byte : %d" % (
                        4 - layer, key.encode('hex'), ord(padding_block[-1]))
コード例 #12
0
            break
        except Exception, e:
            print e
    key = ""
    while True:
        data = client.recv(1024)
        if data:
            key += data
        else:
            break
    client.close()

    key = key.rstrip()

    aes = AESCipher(key)
    decrypted = aes.decrypt(buf)
    if decrypted.endswith('\x90'):
        print "Decryption successful!"
        print "Decrypted: %s" % print_in_hex(decrypted)
        sc = c_char_p(decrypted)
        size = len(decrypted)
        addr = c_void_p(libc.valloc(size))
        memmove(addr, sc, size)
        libc.mprotect(addr, size, 0x7)
        run = cast(addr, CFUNCTYPE(c_void_p))
        run()
        sys.exit(0)
    else:
        print "Decryption not successful! retrying in %d secs" % time_to_wait
        time.sleep(time_to_wait)
コード例 #13
0
ファイル: crack.py プロジェクト: AdrianHsu/ctf-aes-mitm
from string import printable

ciphertext = open('flag.encrypted', 'rb').read()
printable = printable[:-5]

password = ""
charset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

for i in range(4):
    print("round {}".format(i + 1))
    possibilities = []
    for c1, c2 in product(charset, repeat=2):
        if c1 not in printable or c2 not in printable:
            continue
        me = (c1 + c2).encode('utf-8')
        key = sha256(me).digest()
        cipher = AESCipher(key)
        dec = cipher.decrypt(ciphertext)

        n = ord(chr(dec[-1]))
        if n < 32 and all(i == dec[-1] for i in dec[-n:]):
            print('padding length: {}'.format(n))
            possibilities.append((n, c1 + c2, dec))
    _, key, ciphertext = sorted(possibilities, reverse=True)[0]
    ciphertext = AESCipher._unpad(ciphertext)
    password = key + password
    print('found bytes: {}'.format(key))

with open('flag.dec', 'wb') as f:
    f.write(ciphertext)
print(password)
コード例 #14
0
from hashlib import sha256
from itertools import product
from string import printable

ciphertext = open('flag.encrypted', 'rb').read()
printable = printable[:-5]

password = ""
for i in range(4):
	print("round {}".format(i + 1))
	possibilities = []
	for i,j in product(range(256), repeat=2):
		c1, c2 = chr(i), chr(j)
		if c1 not in printable or c2 not in printable:
			continue
		key = sha256(chr(i) + chr(j)).digest()
		cipher = AESCipher(key)
		dec = cipher.decrypt(ciphertext)
		n = ord(dec[-1])
		if n < 32 and all(i == dec[-1] for i in dec[-n:]):
			print('padding length: {}'.format(n))
			possibilities.append((n, chr(i) + chr(j), dec))
	_, key, ciphertext = sorted(possibilities, reverse=True)[0]
	ciphertext = AESCipher._unpad(ciphertext)
	password = key + password
	print('found bytes: {}'.format(key))

with open('flag.dec', 'wb') as f:
	f.write(ciphertext)
print(password)