Search code examples
python-3.xbinascii

Python: Alternative to binascii b-function for predefined string


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!


Solution

  • 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