I have buf="\x00\xFF\xFF\xFF\xFF\x00"
How can I make the "\xFF\xFF\xFF\xFF" randomized?
>>> import os
>>> "\x00"+os.urandom(4)+"\x00"
'\x00!\xc0zK\x00'
/dev/urandom is using some hardware random number generator, its numbers are also pseudo-random. A deterministic machine will always generate pseudo-random numbers.urandomhere /dev/random is a more random source of randomness, but blocks whenever there is not enough entropy.An alternative way to obtaining a secure random sequence of bytes could be to use the standard library secrets module, available since Python 3.6.
Example, based on the given question:
import secrets
b"\x00" + secrets.token_bytes(4) + b"\x00"
More information can be found at: https://docs.python.org/3/library/secrets.html
Python 3.9 adds a new random.randbytes method. This method generates random bytes:
from random import randbytes
randbytes(4)
Output:
b'\xf3\xf5\xf8\x98'
Be careful though. It should be used only when you are not dealing with cryptography. As stated in the docs:
This method should not be used for generating security tokens. Use
secrets.token_bytes()instead.
random.seed: stackoverflow.com/questions/32329381/…randbytes is literally implemented as random.getrandbits(n * 8).to_bytes(n, 'little')On POSIX platforms:
open("/dev/urandom","rb").read(4)
Use /dev/random for better randomization.
prng's than os.urandom.This can be used to generate a string of random bytes (replace n with the desired amount):
import random
random_bytes = bytes([random.randrange(0, 256) for _ in range(0, n)])
-or-
random_bytes = bytes([random.randint(0, 255) for _ in range(0, n)])
-or-
random_bytes = bytes([random.getrandbits(8) for _ in range(0, n)])
The answer to the specific question would then be:
import random
buf = b'\x00' + bytes([random.randrange(0, 256) for _ in range(0, 4)]) + b'\x00'
-or-
buf = b'\x00' + bytes([random.randint(0, 255) for _ in range(0, 4)]) + b'\x00'
-or-
buf = b'\x00' + bytes([random.getrandbits(8) for _ in range(0, 4)]) + b'\x00'
As others pointed out, this should not be used for cryptography, but for everything else it should be perfectly fine.
Simple:
import functools, random, operator
functools.reduce(operator.add, ('%c' % random.randint(0, 255) for i in range(4)))
"".join(...) is the preferred way to turn a sequence into a stringfrom random import randint
rstr = ''.join( randint(0, 255) for i in range(4) )
NameError: name 'buf' is not definedstring so change the int to string character. Code: rstr = "".join( chr(randint(0, 255)) for i in range(4)).