python os.urandom 安全_python – os.urandom()解码问题

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

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

但它抛出了这个错误:

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

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

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

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

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

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

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

它说

AttributeError: ‘bytes’ object has no attribute ‘codecs’

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

解决方法:

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

>>> import binascii

>>> binascii.hexlify(os.urandom(32))

b'daae7948824525c1b8b59f9d5a75e9c0404e46259c7b1e17a4654a7e73c91b87'

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

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

'daae7948824525c1b8b59f9d5a75e9c0404e46259c7b1e17a4654a7e73c91b87'

标签:python,windows,python-3-x,decode,python-3-4

来源: https://codeday.me/bug/20190716/1476699.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值