0

Can you please help me to understand such a simple subject. I need to produce a serie of random hexadecimal strings for which I'm using:

import secrets
x = secrets.token_hex(32)

This gives me something like this:

d6d09acbe78c269147803b8c351214a6e5f39093ca315c47e1126360d0df5369

Which is totally fine. Now I need to pass it through a SHA256 hash for which I'm using:

h = hashlib.new('sha256')
print (h.update(x))

Getting the error:

TypeError: Unicode-objects must be encoded before hashing

I read I need to encode the string before passing the hash using .encode() obtaining a completelly weird:

b'd6d09acbe78c269147803b8c351214a6e5f39093ca315c47e1126360d0df5369'

, and a 'none' result as the hash.

Can you please tell me whats going on here.

Thanks a lot gentls.

Felipe Galaz
  • 5
  • 1
  • 1
  • 6
  • `h.update(x.encode())` works fine for me. Which version of Python are you using? I see that you are trying to print the return value of `.update(x)`, which is `None`. You should print `h.hexdigest()` after running `.update()`. See [docs](https://docs.python.org/3/library/hashlib.html#simple-hashing) for details. – Selcuk Jan 30 '20 at 04:49

1 Answers1

0

You are trying to print the output of h.update(), which will be None as it doesnt return anything. Instead use

h.update(x.encode())
print(h.hexdigest())

to print out a hash string.

Eriall
  • 177
  • 1
  • 7