0

I want to use the hashlib function which requires byte-representation of strings. In this example from the Python documentation they solve this by putting a 'b' in front of the string:

>>> import hashlib, binascii
>>> dk = hashlib.pbkdf2_hmac('sha256', b'password', b'salt', 100000)

This only seems to work when the string is defined in the function call. I would like to use predefined strings but I cannot seem to use the b-function. I would like to do something like:

>>> import hashlib, binascii
>>> mystr = 'password'
>>> dk = hashlib.pbkdf2_hmac('sha256', b(mystr), b'salt', 100000)

Or

>>> dk = hashlib.pbkdf2_hmac('sha256', b mystr, b'salt', 100000)

Obviously, non of these worked. I researched and found some more complex solutions, but I wonder if there is any solution for predefined strings that is as smooth as for strings defined directly in the function.

Thanks!

reaktard
  • 23
  • 6

2 Answers2

0

So what did the trick was

bytes(mystr, 'utf8')
reaktard
  • 23
  • 6
0

You can use bytes(my_string) or bytes(my_string, encoding) to convert a string to bytes. No need for the binascii module.

Documentation can be found here: https://docs.python.org/3/library/functions.html#bytes

Byte Commander
  • 6,506
  • 6
  • 44
  • 71