Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

random byte string in python

I have buf="\x00\xFF\xFF\xFF\xFF\x00"

how can i get the "\xFF\xFF\xFF\xFF" randomized?

like image 528
zack Avatar asked Mar 31 '11 04:03

zack


People also ask

What is byte string in Python?

In Python, a byte string is just that: a sequence of bytes. It isn't human-readable. Under the hood, everything must be converted to a byte string before it can be stored in a computer. On the other hand, a character string, often just called a "string", is a sequence of characters. It is human-readable.

How many bytes is a string in Python?

2 bytes per char (UCS-2 encoding)

What is a random byte?

random_bytes(int $length ): string. Generates an arbitrary length string of cryptographic random bytes that are suitable for cryptographic use, such as when generating salts, keys or initialization vectors.


2 Answers

>>> import os >>> "\x00"+os.urandom(4)+"\x00" '\x00!\xc0zK\x00' 
like image 55
John La Rooy Avatar answered Oct 13 '22 01:10

John La Rooy


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

like image 44
Tatiana Al-Chueyr Avatar answered Oct 13 '22 01:10

Tatiana Al-Chueyr