How to create a hash using the hashlib library using the "time.time()" method in Python3

Asked

Viewed 513 times

1

Hello, I have the following situation:

  • I have to create a hexdigest of a concatenation of 2 numbers transformed into a string.
  • For this, I must use the library hashlib and the project must be in python.

Follow my code so far:

import time
import hashlib

num1 = 123456
num2 = time.time()

str1 = str(num1)
str2 = str(num2)

hash = hashlib.sha1(str1 + str2)
hexhash = hash.hexdigest()

print(hexhash)

The problem is that while trying to run the above code, it is returning the error message:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Unicode-objects must be encoded before hashing

What I need to do to create this hexdigest using these variables?

1 answer

1


Your strings are in the wrong format. They must be encoded before hashing through one of the following methods:

(str1).encode('utf-8')

or

num1 = b'123456'

Or you can do everything in one line only through

hexhash = hashlib.sha1((str1 + str2).encode('utf-8')).hexdigest()
  • hum.. I didn’t know the Encounter method... has 1 week I’m dealing with python, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.