9

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.

ivanleoncz
  • 9,070
  • 7
  • 57
  • 49

3 Answers3

21

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'
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • _private_key = binascii.hexlify(os.urandom(32)).decode('hex') LookupError: 'hex' is not a text encoding; use codecs.decode() to handle arbitrary codecs_ –  Dec 28 '14 at 23:59
  • 2
    @tamamdir, Remove `.decode('hex')` part. Just `binascii.hexlify(os.urandom(32))` or `binascii.hexlify(os.urandom(32)).decode()` – falsetru Dec 28 '14 at 23:59
3

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.

jfs
  • 399,953
  • 195
  • 994
  • 1,670
0
private_key = "".join(["%02x" % ord(x) for x in os.urandom(32)])