sha1 encryption with python

Asked

Viewed 1,587 times

1

I need to generate a sha1 encryption of a string value from a JSON file, but I’m not getting it. Does anyone know where I’m going wrong with my code? The code opens the json file, takes the String that is in the field1 key transforms into sha1 and then writes the value to the field2 key, saves and closes the json file.

import requests
import json
import hashlib

arq = open('arq.json', 'r')
data = json.load(arq)
arq.close()

resumo = hashlib.sha1(data['campo1']).hexdigest()
data['campo2'] = resumo

arq = open('arq.json', 'w+')
arq.write(json.dumps(data))
arq.close()

Giving a Typeerror error: Unicode-Objects must be encoded before hashing

  • What’s going on? The code seems correct. If the external structure of your json is a list and not a dictionary, it will fail. As you will re-write the whole file, "w" mode, not "w+" should be used.

  • is giving an Encode error TypeError: Unicode-objects must be encoded before hashing

  • Ah - now it is possible to answer the question, without having to (1) write your code to a local program, (2) create an "out of the blue" example JSON that is compatible with the program and (3) run the program to see the error.

1 answer

3


All cryptographic functions work on hashes, not on text. Since the same text can have several different representations as bytes, depending on the encoding chosen.

The encoding used throughout the world, in mobile phones and in supercomputing for texts is the universal "utf-8" encoding. However, Windows continues, for historical reasons, using local encodings for files and filesystem. Both the utf-8 and latin-1 encoding (used by Windows in Western languages) would work well there - but it’s important that the encoding is the same as the one already in the file - so you can take advantage that it’s open for reading, and take the encoding used by Python -

import requests
import json
import hashlib

with open('arq.json', 'r') as arq:  # Sintaxe recomendada para abrir arquivos - garante o close automático
   data = json.load(arq)
   encoding = arq.encoding


resumo = hashlib.sha1(data['campo1'].encode(encoding)).hexdigest()
data['campo2'] = resumo

with open('arq.json', 'w') as arq:
   json.dump(data, arq)

Browser other questions tagged

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