Python Hashlib Function: Typeerror: update() takes in keyword Arguments

Asked

Viewed 171 times

1

I am working on a script where in one of the steps I will have to use the function hashlib to convert one string list to another via SHA256. However, I’m having some problems that I haven’t been able to solve yet.

One of them is in relation to the code below:

import hashlib
h = hashlib.sha256()
h.update("uma frase qualquer",encoding='utf-8')
print(h.hexdigest())

Initially, error appeared requesting encode. Includes the encoding in the update. But now the error I can’t fix is:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-16-c4c9e8e0d84d> in <module>
      2 
      3 h = hashlib.sha256()
----> 4 h.update("uma frase qualquer",encoding='utf-8')
      5 print(h.hexdigest())

TypeError: update() takes no keyword arguments

Does anyone know how to solve these "takes" points in the keyword Arguments? And if someone has some tips how to convert lists of strings using the hashlib (more specifically, SHA256), I accept also.

1 answer

2


If you look at documentation of update, will see that he only receives one parameter, which is a bytes-like Object (but as you are passing two parameters, gives error).

In case, if you want to convert the string to bytes using a specific encoding, just use the method encode, which returns an object of the type bytes (just what update accurate):

import hashlib

h = hashlib.sha256()
h.update("uma frase qualquer".encode('utf-8'))
print(h.hexdigest()) # 2c7352c8cd51b0c07bc83c86e7c8e0fdace53e236fae91821ebfbfacc0a6592e

As for "convert a list of strings", it is not very clear. You have a list of strings and for each string you want to calculate the respective hash?

If so, an alternative is to create a function that calculates the hash of a string, and then use map to apply this function to each element in the list:

import hashlib

# calcula o hash de uma string
def hash256(s):
    h = hashlib.sha256()
    h.update(s.encode('utf-8'))
    return h.hexdigest()

lista = [ 'abc', 'def', 'ghi' ]
# cria outra lista com os hashes de cada string da lista acima
hashes = list(map(hash256, lista))
print(hashes) # ['ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad', 'cb8379ac2098aa165029e3938a51da0bcecfc008fd6795f401178647f96c5b34', '50ae61e841fac4e8f9e40baf2ad36ec868922ea48368c18f9535e47db56dd7fb']

Thus, the list hashes contains the hashes of each string in the original list (in this case, the hashes of the strings 'abc', 'def' and 'ghi').

Browser other questions tagged

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