如何将 python urandom 转换为字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17958347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:35:21  来源:igfitidea点击:

How can I convert a python urandom to a string?

pythonstringrandompython-3.xbyte

提问by user1876508

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

如果我调用 os.urandom(64),我会得到 64 个随机字节。参考Convert bytes to a Python string我试过

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

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

但得到回溯错误,指出字节不在 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'\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'

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.

是否有完整的方法将这些字节解码为某种字符串表示?我正在生成 sudo 随机令牌以跟踪跨多个数据库引擎的相关文档。

采纳答案by user1876508

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

下面的代码适用于 Python 2.7 和 3:

from base64 import b64encode
from os import urandom

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

回答by Martijn Pieters

You have random bytes; I'd be very surprised if that ever was decodable to a string.

你有随机字节;如果可以将其解码为字符串,我会感到非常惊讶。

If you haveto have a unicode string, decode from Latin-1:

如果您必须有一个 unicode 字符串,请从 Latin-1 解码:

a.decode('latin1')

because it maps bytes one-on-one to corresponding Unicode code points.

因为它将字节一对一映射到相应的 Unicode 代码点。

回答by Rob Watts

You can use base-64 encoding. In this case:

您可以使用 base-64 编码。在这种情况下:

a = os.urandom(64)
a.encode('base-64')

Also note that I'm using encodehere rather than decode, as decodeis trying to take it from whatever format you specify into unicode. So in your example, you're treating the random bytes as if they form a valid utf-8string, which is rarely going to be the case with random bytes.

另请注意,我在encode这里使用而不是decode,因为decode试图将它从您指定的任何格式转换为 unicode。因此,在您的示例中,您将随机字节视为形成有效utf-8字符串一样,而随机字节很少会出现这种情况。