如何将python urandom转换为字符串? [英] How can I convert a python urandom to a string?

查看:501
本文介绍了如何将python urandom转换为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我调用os.urandom(64),则会得到64个随机字节.关于将字节转换为Python字符串我尝试过

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")

,但是出现了回溯错误,指出字节不在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

带有字节

b'\x8bz\xaf$\xb6\x93q\xef\x94\x99$\x8c\x1eO\xeb\xed\x03O\xc6L%\xe70\xf9\xd8
\xa4\xac\x01\xe1\xb5\x0bM#\x19\xea+\x81\xdc\xcb\xed7O\xec\xf5\\}\x029\x122
\x8b\xbd\xa9\xca\xb2\x88\r+\x88\xf0\xeaE\x9c'

是否存在将这些字节解码为某种字符串表示形式的完全验证方法?我正在生成sudo随机令牌,以跟踪多个数据库引擎中的相关文档.

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.

推荐答案

下面的代码将同时在Python 2.7和3上运行.

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')

这篇关于如何将python urandom转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆