0

Does it really needed to use letter b when hashing a key? I'm just confused of its usage. Can I use the method 2 without using b'? And how can I insert a variable in method one?

from hashlib import blake2b

key = 'Hello'
blake2b(b'key').hexdigest()

versus


from hashlib import blake2b

key = 'Hello'
blake2b(key).hexdigest()
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
Jom
  • 35
  • 8
  • 2
    It means that it is actually a *binary string*: a list of bytes. But the bytes are here represented by their ASCII equivalent. The two are completely different. The fact that you write `key` has *nothing* to do with a possible variable `key`. – Willem Van Onsem Sep 02 '17 at 13:21
  • Willem Van Onsem So how can I insert the variable name within the blake2b() function? – Jom Sep 02 '17 at 13:26
  • Your second example above should work as you intend it to. Does it not? – sma Sep 02 '17 at 13:28
  • 2
    https://stackoverflow.com/questions/6269765/what-does-the-b-character-do-in-front-of-a-string-literal – timgeb Sep 02 '17 at 13:29
  • 1
    If you are using Python 2, `b'foo'` is identical to `'foo'`. – timgeb Sep 02 '17 at 13:30

1 Answers1

1

b in front of strings stands for bytes.

  1. Your first example

    from hashlib import blake2b
    
    key = 'Hello'
    blake2b(b'key').hexdigest()
    

    Here you pass string 'key' as bytes into blake2b. That doesn't insert the contents of variable key.

  2. Second example:

    from hashlib import blake2b
    
    key = 'Hello'
    blake2b(key).hexdigest()
    

    inserts variable key but as a string and not its bytes representation.

What you want to do is

from hashlib import blake2b

key = 'Hello'
blake2b(key.encode()).hexdigest()

The last line constructs a string using str.format() which replaces {0} with first argument of format. By doing this you can prepend b in front of the string.

campovski
  • 2,979
  • 19
  • 38
  • 2
    The string interpolation is probably unnecessary here. `key=b'Hello'` would also work. – sma Sep 02 '17 at 13:30
  • That is true, but you cannot do this if string gets from some other source, let's say `key = input()`. – campovski Sep 02 '17 at 13:32
  • bytestrings don't have a `format` method. You can convert `str` to `bytes` with `encode`. – interjay Sep 02 '17 at 13:38
  • I think I found the solution. Since I'm using Python 3.x, so it's mandatory to use b', what I did was this from hashlib import blake2b key = "b'Hello'" blake2b(key).hexdigest() – Jom Sep 02 '17 at 13:43
  • 1
    Again, what if the `key` isn't typed there as it is but gets from other source? – campovski Sep 02 '17 at 13:47
  • 1
    Above example has been edited and tested... – campovski Sep 02 '17 at 13:48