def test_write( tmp_path: Path, # pylint: disable=redefined-outer-name ram_usage: Callable[[], int], ) -> None: nb_blocks = 10 seed(0) one_block_memory: Optional[int] = None with XZFile(tmp_path / "archive.xz", "w") as xz_file: for i in range(nb_blocks): xz_file.change_block() xz_file.write(randbytes(BLOCK_SIZE)) if one_block_memory is None: one_block_memory = ram_usage() else: assert ( # should not use much more memory, take 2 as error margin ram_usage() < one_block_memory * 2 ), f"Consumes too much RAM (at {i / nb_blocks:.0f}%)"
# SECRECT KEY import random SECRET_KEY = random.randbytes(19) # Database SQLALCHEMY_DATABASE_URI="mysql+pymysql://root:@localhost/ospos?host=localhost?port=3306" SQLALCHEMY_ECHO=False SQLALCHEMY_TRACK_MODIFICATIONS=False
def MakeEthernetID(): ba = bytearray(random.randbytes(6)) ba[0] |= 0x2 ba[0] &= ~0x1 return "%02x:%02x:%02x:%02x:%02x:%02x" % (ba[0], ba[1], ba[2], ba[3], ba[4], ba[5])
def consume_new_walk_logs( rsr: RedisStreamReader, gamestate_id: int, engine: Engine, engineserver_id: int, ): stream_name = f"gamestate-{gamestate_id}" logs = rsr.read(stream_name) consumable_logs = [ log["item"] for log in logs if log["engineserver_id"] != engineserver_id ] old_times_visited = engine.root_node.times_visited engine.consume_walk_log(consumable_logs) visited_increase = engine.root_node.times_visited - old_times_visited num_walk_results = sum(1 for log in consumable_logs if log["event-type"] == "walk-result") assert visited_increase == num_walk_results if __name__ == "__main__": redis_config = eng_types.RedisConfig( host="localhost", port=6379, db=0, ) engineserver_id = int.from_bytes(random.randbytes(4), "big") serve(redis_config, engineserver_id)
#!/bin/python3 from hashlib import sha256 from random import randbytes from sys import argv # generates n random test vectors, and computes the hash for each # then writes both the vector and the hash in two separate files f1 = open("inputs.in", "wb") f2 = open("hashes.hash", "wb") for i in range(int(argv[1])): b = randbytes(i+1) h = sha256(b).digest() f1.write(b) f2.write(h) f1.close() f2.close()
def generateBinary(self, length: int) -> bytes: print("Generating binary content...") binaryContent: bytes = random.randbytes(length) return binaryContent
from chatroom.chatroom import Chatroom, ChatroomList from chatroom.public_chatroom import PublicChatroom from gameroom.classic_gameroom import ClassicGameroom from gameroom.coop_gameroom import CoopGameroom from gameroom.free_gameroom import FreeGameroom from gameroom.gameroom import Gameroom, GameroomList from gameroom.solo_gameroom import SoloGameroom from gameroom.tuto_gameroom import TutoGameroom from message import UserMessage from mongo_manager import AbsentEntryError, MissingParameterError, MongoManager from user import User, UserList Payload.max_decode_packets = 1000 app = Flask(__name__) app.config['SECRET_KEY'] = random.randbytes(16) socketio = SocketIO(app, cors_allowed_origins="*", ping_timeout=12000) connectedUsers = {} connected_users_list = UserList() db = MongoManager() chatrooms = ChatroomList() gamerooms = GameroomList() ######### # UTILS # ######### def verify_session(event): def verify_session_decor(fn): def wrapper(*args, **kwargs):
def password_hash(password: str, *, salt: bytes = None) -> str: salt = salt or random.randbytes(16) hashed = hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 100000) return f"{salt.hex()}:{hashed.hex()}"
for i in range(1,n+1): coeffs.append(next_coeff(coeffs[i-1])) def calc_y(x, coeffs): y = 0 for i, coeff in enumerate(coeffs): y +=coeff *x**i return y%p p = 92434467187580489687 k = 10 n = 18 # from msg.enc x, y = 21202245407317581090, 11086299714260406068 coeff1 = 93526756371754197321930622219489764824 enc_flag = bytes.fromhex("1aaad05f3f187bcbb3fb5c9e233ea339082062fc10a59604d96bcc38d0af92cd842ad7301b5b72bd5378265dae0bc1c1e9f09a90c97b35cfadbcfe259021ce495e9b91d29f563ae7d49b66296f15e7999c9e547fac6f1a2ee682579143da511475ea791d24b5df6affb33147d57718eaa5b1b578230d97f395c458fc2c9c36525db1ba7b1097ad8f5df079994b383b32695ed9a372ea9a0eb1c6c18b3d3d43bd2db598667ef4f80845424d6c75abc88b59ef7c119d505cd696ed01c65f374a0df3f331d7347052faab63f76f587400b6a6f8b718df1db9cebe46a4ec6529bc226627d39baca7716a4c11be6f884c371b08d87c9e432af58c030382b737b9bb63045268a18455b9f1c4011a984a818a5427231320ee7eca39bdfe175333341b7c") coeffs = [coeff1] calc_coeffs(coeffs) coeffs = coeffs[:k-1] secret = (y - x*calc_y(x, coeffs))%p seed(secret) key = randbytes(16) cipher = AES.new(key, AES.MODE_ECB) print(cipher.decrypt(enc_flag).decode()) # HTB{1_d1dnt_kn0w_0n3_sh4r3_w45_3n0u9h!1337}
def inner(): nonce = list(random.randbytes(8)) rx_nonce_history.append(nonce) return nonce
def network_key(): yield list(random.randbytes(16))
def update_event(self, inp=-1): self.set_output_val(0, random.randbytes(self.input(0)))
def generate_id(): return int(random.randbytes(4).hex(), 16)
contract_address = 'KT1Udix7b2UUnnqSzAk6JsqDy7m1ecwTG1LB' # The contract address ############################################################## pytezos = pytezos.using(shell='https://mainnet-tezos.giganode.io', key=base58key) contract = pytezos.contract(contract_address) challenge_bytes = get_challenge(contract) min0s = "0" * min_0s_for_prize(contract) print('running with challenge:', challenge_bytes.hex()) print('current difficulty:', min0s) while True: # Pick a random number nonce_bytes = random.randbytes(16) # Generate a solution hash tohash = challenge_bytes + nonce_bytes + address_bytes solution = hashlib.blake2b(tohash, digest_size=32).hexdigest() # Check if the current solution matches the current difficulty test if solution.startswith(min0s): print("****************FOUND********************") print("nonce: [%s], solution: [%s], challenge: [%s]" % (nonce_bytes.hex(), solution, challenge_bytes.hex())) print(send_transaction(contract, nonce_bytes, solution)) # Poll the contract for a new challenge value every 5 seconds # WARNING: if you are in a mining battle with someone # or if the transaction fails for whatever reason,
def __createPrivateKey(self): # private key 32 bytes self.__private_key = randbytes(self.__byte)
from random import randbytes from typing import Tuple, List from struct import pack, unpack, calcsize from hashlib import md5, sha1, sha256, sha512 from ctypes import Structure, BigEndianStructure, sizeof SEEK_SET = 0 SEEK_CUR = 1 SEEK_END = 2 MD5_DIGEST_LEN = 16 SHA1_DIGEST_LEN = 20 SHA256_DIGEST_LEN = 32 SHA512_DIGEST_LEN = 64 rand_str = lambda n: randbytes(n).hex().upper() class Endian(IntEnum): LITTLE = 0 BIG = 1 NETWORK = 2 NATIVE = 3 class Type(IntEnum): BYTE = 0 UBYTE = 1 BYTE_ARRAY = 2 UBYTE_ARRAY = 3 UINT8 = 4
def garbage(): ## {{{ from random import randbytes while True: text = randbytes(80).decode(errors='ignore') print(text, end='') dorm(0.01)
def generate_nonce(cls) -> List[int]: return list(random.randbytes(8))
#!/usr/bin/env python3 import random import sys import time from datetime import timedelta random.seed() to_write = total_len = random.randint(1, 10*1024*1024) sys.stdout.write("Content-Type: application/octet-stream\n") sys.stdout.write(f"Content-Length: {total_len}\n") sys.stdout.write("\n") sys.stdout.flush() while to_write > 0: len = random.randint(1, 1024*1024) len = min(len, to_write) sys.stdout.buffer.write(random.randbytes(len)) to_write -= len delay = timedelta(seconds=random.uniform(0.0, 0.5)) time.sleep(delay.total_seconds()) sys.stdout.flush()
import random import subprocess import time step = 1000000 times = 20 client = "ClientCP1" server = "ServerCP1" with open("stats/time_" + client + ".csv", "w") as outfile: for size in range(step, step * (times + 1), step): print(size) with open("client_res/test.bin", "wb") as f: f.write(random.randbytes(size)) start = time.time() subprocess.call(["java", client, "test.bin"]) runtime = time.time() - start outfile.write(f"{size}\t{runtime}\n")
def new_message_id(): return randbytes(32)
import random with open("test.photo" , "wb") as f: for i in range(100): f.write(random.randbytes(10))
def __init__(self, data): self.data = ''.join('{0:b}'.format(ord(_)).zfill(8) for _ in data) self.secret = ''.join('{0:b}'.format(_).zfill(8) for _ in random.randbytes(len(self.data) // 8))
import random if __name__ == '__main__': while True: print(random.randbytes(80).decode(errors='ignore'), end='')
def setup(self, browser): link = " " email = random.randint(1, 9) + "@fakemail.org" password = random.randbytes(9)
print(sum(listaNum)) print('______________________________________________') # promedio de datos de un conjunto de datos import statistics promedio = statistics.mean(listaNum) print(promedio) # El que mas se repite mode: print(statistics.mode(listaNum)) print('______________________________________________') # Matematica: import math print(math.pi) # pi print(math.sin(45)) # seno print(math.pow(2, 2)) # potencia print(math.factorial(4)) # factorial print(math.sqrt(25)) # raiz cuadrada print(math.trunc(45.99999999)) # truncar decimales, se los quita print(round(45.99999999)) # redondea print('______________________________________________') # aleatorios import random print(random.randint(10, 20)) # numero aleatorio entre el rango dado print(random.random()) # numeros aleatorios entre 0 y 1 print(random.randbytes(5)) # los bytes print('______________________________________________')
import sys import random import socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) ip = sys.argv[1] if sys.argv[2] == "*": port = 0 else: port = int(sys.argv[2]) max_buffer_size = int(sys.argv[3]) packet = 0 while True: buffer = bytes(random.randbytes(max_buffer_size)) sock.sendto(buffer, (ip, port)) if sys.argv[2] == "*": port += 1 packet += 1 print("packet_number={0},size={1},ip={2},port={3}".format( packet, len(buffer), ip, port)) if port >= 65534: port = 1
def setUp(self): self.h = 60 self.w = 60 self.kutter = Kutter() self.container = bytearray(randbytes(self.h * self.w)) self.data = 'test'
def __init__(self, torrent: Torrent): self.torrent = torrent self.peer_id: ByteString = bytes(b"-AP0010-") + random.randbytes(12)
def handle(self): try: addr = self.client_address[0] port = self.client_address[1] dport = self.server.server_address[1] data = self.request[0] sock = self.request[1] first = False last = False # no need to check for validity, any packet is accepted # IP addresses in transaction log and database will be stored as integers/long addr_int = utils.addr_to_int(addr) now = datetime.datetime.now() log_msg = 'New genericpot packet received' # check if the request from this IP address was already received - ENTERING CRITICAL SECTION HERE! with self.server.tx_log_lock: # since generic pot can be ran on any port, use port that the service is running on for # attack discrimination req_key = (addr_int, dport) if req_key in self.server.transaction_log: addr_log = self.server.transaction_log[req_key] # check if this is an already existing attack or a new attack # attack is classified as NEW if more than new_attack_duration_interval # minutes have passed since the last seen packet if addr_log[ 'last_seen'] + self.server.new_attack_interval < now: # consider this as a new attack, reset cache data first = True addr_log['count'] = 1 addr_log['last_seen'] = now log_msg = 'New attack detected' else: # update transaction log and database last-seen time and packet count and do not respond to the packet addr_log['last_seen'] = now addr_log['count'] += 1 # add the IP address to the request cache set - this set will be frequently flushed to DB self.server.ip_log.add(req_key) # if count >= threshold, ignore the packet, never respond if addr_log['count'] > self.server.threshold: return # log reaching of threshold and mark packet as last that will be accepted elif addr_log['count'] == self.server.threshold: last = True self.logger.info( 'Threshold reached for host %s and port %d - will not respond to this host' % (addr, dport)) log_msg = 'Last packet - threshold reached' else: # add host to transaction log first = True self.server.transaction_log[req_key] = {} self.server.transaction_log[req_key]['last_seen'] = now self.server.transaction_log[req_key]['count'] = 1 if self.random: # if multiplier is specified, response size is multiplied by request size # do not create response that is larger than 1 MB! resp_size = self.response_size if isinstance(resp_size, float): resp_size = min(int(len(data) * self.response_size), 1048576) response = random.randbytes(resp_size) else: # not random, use predefined response response = self.response resp_size = self.response_size sock.sendto(response, self.client_address) if first or last: b64_req = base64.b64encode(data) input_size = len(data) self.log_packet(log_msg, addr, port, dport, now, b64_req, input_size, resp_size, last) except Exception: t = traceback.format_exc() self.logger.error( 'Unknown error during communication with %s:%d - %s' % (addr, port, base64.b64encode(data))) self.logger.error('Stacktrace: %s' % t)