os.urandom()解码问题

5 python string hex ascii decode

我试图得到一个private_key,我试过这个:

private_key = os.urandom(32).encode('hex')
Run Code Online (Sandbox Code Playgroud)

但它抛出了这个错误:

AttributeError: 'bytes' object has no attribute 'encode'
Run Code Online (Sandbox Code Playgroud)

所以我检查问题并解决了,在Python3x字节中只能解码.然后我将其更改为:

private_key = os.urandom(32).decode('hex')
Run Code Online (Sandbox Code Playgroud)

但现在它抛出了这个错误:

LookupError: 'hex' is not a text encoding; use codecs.decode() to handle arbitrary codecs
Run Code Online (Sandbox Code Playgroud)

我真的不明白为什么.当我在最后一次错误后尝试这个时;

private_key = os.urandom(32).codecs.decode('hex')
Run Code Online (Sandbox Code Playgroud)

它说

AttributeError:'bytes'对象没有属性'codecs'

所以我卡住了,我该怎么做才能解决这个问题?我听说这是在Python 2x中工作,但我需要在3x中使用它.

fal*_*tru 14

使用binascii.hexlify.它适用于Python 2.x和Python 3.x.

>>> import binascii
>>> binascii.hexlify(os.urandom(32))
b'daae7948824525c1b8b59f9d5a75e9c0404e46259c7b1e17a4654a7e73c91b87'
Run Code Online (Sandbox Code Playgroud)

如果在Python 3.x中需要字符串对象而不是字节对象,请使用decode():

>>> binascii.hexlify(os.urandom(32)).decode()
'daae7948824525c1b8b59f9d5a75e9c0404e46259c7b1e17a4654a7e73c91b87'
Run Code Online (Sandbox Code Playgroud)

  • @tamamdir,删除`.decode('hex')`部分.只是`binascii.hexlify(os.urandom(32))`或`binascii.hexlify(os.urandom(32)).decode()` (2认同)