decode os.urandom() bytes object

核能气质少年 提交于 2019-12-10 13:46:44

问题


Im trying to get a private_key so, I tried this:

private_key = os.urandom(32).encode('hex')

But it throws this error:

AttributeError: 'bytes' object has no attribute 'encode'

So I check questions and solved that, in Python3x bytes can be only decode. Then I change it to:

private_key = os.urandom(32).decode('hex')

But now it throws this error:

LookupError: 'hex' is not a text encoding; use codecs.decode() to handle arbitrary codecs

And I really didnt understand why. When I tried this after last error;

private_key = os.urandom(32).codecs.decode('hex')

It says

AttributeError: 'bytes' object has no attribute 'codecs'

So I stuck, what can I do for fixing this? I heard this is working in Python 2x, but I need to use it in 3x.


回答1:


Use binascii.hexlify. It works both in Python 2.x and Python 3.x.

>>> import binascii
>>> binascii.hexlify(os.urandom(32))
b'daae7948824525c1b8b59f9d5a75e9c0404e46259c7b1e17a4654a7e73c91b87'

If you need a string object instead of a bytes object in Python 3.x, use decode():

>>> binascii.hexlify(os.urandom(32)).decode()
'daae7948824525c1b8b59f9d5a75e9c0404e46259c7b1e17a4654a7e73c91b87'



回答2:


In Python 3, bytes object has no .encode() method (to strengthen Unicode text vs. binary data (bytes) distinction).

For bytes to bytes conversions, you could use codecs.encode() method:

import codecs
import os

print(codecs.encode(os.urandom(32), 'hex').decode())

And in reverse:

print(codecs.decode(hex_text, 'hex')) # print representation of bytes object

Note: there is no .decode() call because bytes returned by os.urandom has no character encoding (it is not a text, it is just a random sequence of bytes).

codecs may use binascii.hexlify, binascii.unhexlify internally.




回答3:


private_key = "".join(["%02x" % ord(x) for x in os.urandom(32)])


来源:https://stackoverflow.com/questions/27681823/decode-os-urandom-bytes-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!