def encryption_oracle(input): pad1 = utils.random_bytes(randomPadLen()) pad2 = utils.random_bytes(randomPadLen()) input = pad1 + input + pad2 if (utils.random_bool()): print('Performing CBC') return ('CBC', AES.CBC_encrypt(AES.randomKey(), input, AES.randomIV())) else: print('Performing ECB') return ('ECB', AES.ECB_encrypt(AES.randomKey(), input))
def hash_work(self, button): if len(self._workpaths) == 0 or self._paths_selected == 0: return self._plugin._modal.show_message('Hashing your work to Matryx') selected_paths = [ wp_entry[0] for wp_entry in self._workpaths.items() if wp_entry[1] ] ipfs_hash = self._plugin._cortex.upload_files(selected_paths) sender = self._plugin._account.address salt = utils.random_bytes() commit_hash = self._plugin._web3.solidity_sha3( ['address', 'bytes32', 'string'], [sender, salt, ipfs_hash]) tx_hash = self._plugin._web3._commit.claimCommit(commit_hash) self._plugin._web3.wait_for_tx(tx_hash) tx_hash = self._plugin._web3._commit.createCommit( '0x' + '0' * 64, False, salt, ipfs_hash, 1) self._plugin._web3.wait_for_tx(tx_hash) if self._is_component: self._plugin._menu_tournament.submit_to_tournament( commit_hash, button) else: self._plugin._modal.show_message( 'Your work has been published to Matryx')
def make_ecb_black_box(): key = random_bytes() def black_box(pt): pt = array('B', pt) + secret_text return encrypt_aes_ecb(key, '', pt) return black_box
def prepare(): with self.db.locked() as conn: while True: try: values["`key`"] = _key = utils.random_bytes(8) conn.insert("files", values) return _key except DBALDriverError: # Error: 1062 (ER_DUP_ENTRY) if conn.error_code() != 1062: raise
def _initialize(self): tag = random_bytes(16) for i in xrange(10): # Redirection handling print "Sending initiator hello" self.produce( InitiatorHello(epd_type=self.epd_type, epd=self.epd, tag=tag)) print "Sent initiator hello" hello_msg = self.consume(lambda msg: (isinstance( msg, ForwardedHelloResponse) or isinstance( msg, ResponderHello)) and msg.f_tag_echo == tag) if isinstance(hello_msg, ForwardedHelloResponse): print "[session_debug] Forward hello received" self.addr = hello_msg.f_addrs[1][1] continue else: break else: print "[session_debug] Max redirection count reached" raise Exception("Redirection error") self.emit("initialized") _dh = dh.generate_dh() self.public_key = _dh["pub"] my_keying = InitiatorInitialKeying(cookie_echo=hello_msg.f_cookie, session_id=self.near_id, public_key=_dh["pub"], certificate=random_bytes(64)) self.peer_id = my_keying.peer_id self.produce(my_keying) keying_msg = self.consume( lambda msg: isinstance(msg, ResponderInitialKeying)) self.far_id = keying_msg.f_session_id shared_key = dh.compute_key(_dh, keying_msg.f_public_key) self.decrypt_key, self.encrypt_key = dh.compute_keys( shared_key, keying_msg.nonce, my_keying.nonce)
def _generate_client_kex_init(): msg = [] msg.append(generate_byte(SSH_MSG_NUMS['SSH_MSG_KEXINIT'])) msg.append(random_bytes(COOKIE_LEN)) msg.append(generate_name_list([KEX_ALGORITHM])) msg.append(generate_name_list([SERVER_HOST_KEY_ALGORITHM])) msg.append(generate_name_list([ENCRYPTION_ALGORITHM])) msg.append(generate_name_list([ENCRYPTION_ALGORITHM])) msg.append(generate_name_list([MAC_ALGORITHM])) msg.append(generate_name_list([MAC_ALGORITHM])) msg.append(generate_name_list([COMPRESSION_ALGORITHM])) msg.append(generate_name_list([COMPRESSION_ALGORITHM])) msg.append(generate_name_list([])) msg.append(generate_name_list([])) msg.append(generate_byte(0)) # Additional data being sent = False msg.append('\x00\x00\x00\x00') # Reserved bytes return ''.join(msg)
def send(self, payload): '''Send a packet to the remote server. Assuming the initial connection has completed (i.e. #connect has been called, and returned), this data will be encrypted, and its authenticity guaranteed. Args: payload (string): The data to send to the remote server. ''' # This maths is horrific, but essentially we're calculating how much padding we need to add, # given that we must have at least 4 bytes, and that the total message length must be a multiple # of the AES block length padding_len = MIN_PADDING_LEN padding_len += AES_BLOCK_LEN - ((4 + 1 + len(payload) + padding_len) % AES_BLOCK_LEN) packet_len = 1 + len(payload) + padding_len msg_parts = [] msg_parts.append(generate_uint32(packet_len)) msg_parts.append(generate_byte(padding_len)) msg_parts.append(payload) msg_parts.append(random_bytes(padding_len)) msg = ''.join(msg_parts) # If the packet is encrypted, add the MAC and encrypt the message. The weird order of operations # here is because SSH is encrypt-and-mac (that is, the mac is on the plaintext, which is also # encrypted), rather than encrypt-then-mac or mac-then-encrypt if self._encryption_negotiated: mac = hmac.new( self._integrity_key_client_to_server, generate_uint32(self._packets_sent_counter) + msg, hashlib.sha1 ).digest() msg = self._aes_client_to_server.encrypt(msg) msg += mac self._packets_sent_counter += 1 print colors.magenta('> Sending: %s' % repr(''.join(msg))) self._socket.send(msg)
def send(self, payload): '''Send a packet to the remote server. Assuming the initial connection has completed (i.e. #connect has been called, and returned), this data will be encrypted, and its authenticity guaranteed. Args: payload (string): The data to send to the remote server. ''' # This maths is horrific, but essentially we're calculating how much padding we need to add, # given that we must have at least 4 bytes, and that the total message length must be a multiple # of the AES block length padding_len = MIN_PADDING_LEN padding_len += AES_BLOCK_LEN - ( (4 + 1 + len(payload) + padding_len) % AES_BLOCK_LEN) packet_len = 1 + len(payload) + padding_len msg_parts = [] msg_parts.append(generate_uint32(packet_len)) msg_parts.append(generate_byte(padding_len)) msg_parts.append(payload) msg_parts.append(random_bytes(padding_len)) msg = ''.join(msg_parts) # If the packet is encrypted, add the MAC and encrypt the message. The weird order of operations # here is because SSH is encrypt-and-mac (that is, the mac is on the plaintext, which is also # encrypted), rather than encrypt-then-mac or mac-then-encrypt if self._encryption_negotiated: mac = hmac.new(self._integrity_key_client_to_server, generate_uint32(self._packets_sent_counter) + msg, hashlib.sha1).digest() msg = self._aes_client_to_server.encrypt(msg) msg += mac self._packets_sent_counter += 1 print colors.magenta('> Sending: %s' % repr(''.join(msg))) self._socket.send(msg)
def randomPadLen(): return utils.random_bytes(1)[0] % 6 + 5
def create_session(self, login): session = utils.random_bytes() self.db.execute( "INSERT INTO sess (login, session, expires_at) VALUES(?, ?, NOW() + INTERVAL %d SECOND)" % options.session["lifetime"], login, session) return session
def black_box(plaintext): prepad = random_bytes(randint(5, 10)) postpad = random_bytes(randint(5, 10)) key = random_bytes() iv = random_bytes() return choice(ciphers)(key, iv, prepad + plaintext + postpad)
def __init__(self): self.key = generate_aes_key() self.nonce = random_bytes(8)
def callback(conn): session = utils.random_bytes() conn.execute("DELETE FROM sess WHERE login = ? AND expires_at IS NULL", login) conn.execute("INSERT INTO sess (login, session) VALUES(?)", (login, session)) return session
def _manage(self): while True: type, payload, addr = self.consume() session_message = db.get(type, SessionMessage)(payload) session_message.unpack() session_message.f_type = type if self.raw0: print("\033[95m%s\033[0m" % session_message.explain(c=">>m", compact=False)) continue print session_message.explain(c=">>m", compact=False) if isinstance(session_message, InitiatorHello): if session_message.f_epd_type == 0x0f and self.is_server: # p2p try: addrs, peer_session = self.peers[session_message.f_epd] except KeyError: print "[session_manager_debug] PeerID not found" continue response = ForwardedInitialHello( epd_type=session_message.f_epd_type, epd=session_message.f_epd, tag=session_message.f_tag, addr=addrs[0], addr_is_public=True) #print response.repack().explain(c="<<m", compact=False) peer_session.produce(response) #self.produce((( (response.id, response.pack()), ), addrs[0], False)) if self.middle_p2p_addr: self.p2p.append((addrs[0], session_message.f_epd)) addrs = [self.middle_p2p_addr] response = ForwardedHelloResponse( tag_echo=session_message.f_tag, addrs=[(True, addrs[0])]) print response.repack().explain(c="<<m", compact=False) self.produce( (((response.id, response.pack()), ), addr, True)) else: response = ResponderHello(tag_echo=session_message.f_tag, cookie=addr[0], certificate=random_bytes(64)) if session_message.f_epd_type == 0x0f: response.f_certificate2 = self.public_key print response.repack().explain(c="<<m", compact=False) self.produce( (((response.id, response.pack()), ), addr, True)) elif isinstance(session_message, InitiatorInitialKeying): if session_message.f_cookie_echo != addr[0]: continue session = IncomingSession(addr=addr, near_id=self._session_counter, raw=self.raw) self.emit("new_session", session) self._new.put(session) session.queue.put((type, payload)) self._session_counter += 1 else: for session in self._pending: session.queue.put((type, payload))
def __init__(self): self.key = generate_aes_key() self.iv = random_bytes(16)
#! python import utils import AES import b64 import challenge11 as ch11 key = AES.randomKey() secret_bytes = b64.decode_file('12.txt') random_prefix = utils.random_bytes(utils.random_bytes(1)[0]) def encryption_oracle(bytes): return AES.ECB_encrypt(key, random_prefix + bytes + secret_bytes) def detect_block_size(encryption_oracle): b = encryption_oracle(b'') for i in range(1, 1024): b1 = encryption_oracle(bytes([0] * i)) if (len(b1) != len(b)): return len(b1) - len(b) def detect_prefix_size(block_size, encryption_oracle): # Detect prefix block size for j in range(1, 1024): b = encryption_oracle(bytes([0] * j)) # Check if we find duplicated block for i in range(0, len(b) - block_size, block_size): if b[i:i + block_size] == b[i + block_size:i + 2 * block_size]: # Found!
def random_bytes(handler, length): return utils.random_bytes(length)
def encryption_oracle(plain): prefix = utils.random_bytes(utils.random_num(10, 20)) return MT19937_encrypt(key, prefix + plain)