Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
396 views
in Technique[技术] by (71.8m points)

How can I convert a python urandom to a string?

If I call os.urandom(64), I am given 64 random bytes. With reference to Convert bytes to a Python string I tried

a = os.urandom(64)
a.decode()
a.decode("utf-8")

but got the traceback error stating that the bytes are not in utf-8.

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 0: invalid start byte

with the bytes

b'x8bzxaf$xb6x93qxefx94x99$x8cx1eOxebxedx03Oxc6L%xe70xf9xd8
xa4xacx01xe1xb5x0bM#x19xea+x81xdcxcbxed7Oxecxf5\}x029x122
x8bxbdxa9xcaxb2x88
+x88xf0xeaEx9c'

Is there a fullproof method to decode these bytes into some string representation? I am generating sudo random tokens to keep track of related documents across multiple database engines.

question from:https://stackoverflow.com/questions/17958347/how-can-i-convert-a-python-urandom-to-a-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The code below will work on both Python 2.7 and 3:

from base64 import b64encode
from os import urandom

random_bytes = urandom(64)
token = b64encode(random_bytes).decode('utf-8')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...