random byte string in python
Solution 1:
>>> import os
>>> "\x00"+os.urandom(4)+"\x00"
'\x00!\xc0zK\x00'
Solution 2:
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
Solution 3:
bytearray(random.getrandbits(8) for _ in xrange(size))
Faster than other solutions but not cryptographically secure.
Solution 4:
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.