Python 解码os.Uradom()字节对象

Python 解码os.Uradom()字节对象,python,string,hex,ascii,decode,Python,String,Hex,Ascii,Decode,我正在尝试获取私钥,因此,我尝试了以下方法: private_key = os.urandom(32).encode('hex') 但它抛出了一个错误: AttributeError: 'bytes' object has no attribute 'encode' LookupError: 'hex' is not a text encoding; use codecs.decode() to handle arbitrary codecs 所以我检查了问题并解决了问题,在Python3

我正在尝试获取私钥,因此,我尝试了以下方法:

private_key = os.urandom(32).encode('hex')
但它抛出了一个错误:

AttributeError: 'bytes' object has no attribute 'encode'
LookupError: 'hex' is not a text encoding; use codecs.decode() to handle arbitrary codecs
所以我检查了问题并解决了问题,在Python3x中,字节只能解码。然后我将其更改为:

private_key = os.urandom(32).decode('hex')
但现在它抛出了这个错误:

AttributeError: 'bytes' object has no attribute 'encode'
LookupError: 'hex' is not a text encoding; use codecs.decode() to handle arbitrary codecs
我真的不明白为什么。当我在最后一个错误后尝试这一点时

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

AttributeError:“字节”对象没有属性“编解码器”

所以我卡住了,我能做些什么来修复这个?我听说它在Python 2x中工作,但我需要在3x中使用它。

使用。它在Python2.x和Python3.x中都可以工作

>>> import binascii
>>> binascii.hexlify(os.urandom(32))
b'daae7948824525c1b8b59f9d5a75e9c0404e46259c7b1e17a4654a7e73c91b87'
如果在Python 3.x中需要字符串对象而不是字节对象,请使用
decode()


在Python3中,
bytes
对象没有
.encode()
方法(加强Unicode文本与二进制数据(字节)的区别)

对于字节到字节的转换,您可以:

反过来说:

print(codecs.decode(hex_text, 'hex')) # print representation of bytes object
注意:没有
.decode()
调用,因为
os.uradom
返回的字节没有字符编码(它不是文本,只是一个随机的字节序列)


编解码器
可以在内部使用
binascii.hexlify
binascii.unexlify

private\u key=binascii.hexlify(os.uradom(32)).decode('hex')LookupError:'hex'不是文本编码;使用codecs.decode()处理任意codecs@tamamdir,移除
。解码('hex')
部分。只需
binascii.hexlify(os.uradom(32))
binascii.hexlify(os.uradom(32)).decode()
这会产生错误:TypeError:ord()预期字符串长度为1,但找到int.Mr。所以删除ord(),只留下x。我订购的BSD和Linux上只有2.7版本,可能在其他平台上Uradom()的工作方式不同
private_key = "".join(["%02x" % ord(x) for x in os.urandom(32)])