How to salt a generated hash from a file in Python

Question:

Problem

I wrote a function which signs an uploaded document. In order to increase the security of the function, I would like to add a SALT to it. As I am reading the bytes of the uploaded file, so I guess I would have to prepend or append it somehow?

Code

This is the (working) function without SALT I currently have:

def sign(file):
    with open(private_key_path, 'rb') as f:
        key = f.read()
    hash = SHA256.new(file.read())
    # do signing stuff
    return signature

I tried to update the hash afterwards, but that does not work:

SALT = "random string";
def sign(file):
    with open(private_key_path, 'rb') as f:
        key = f.read()
    h = SHA256.new(file.read())
    hash = h.update(str.encode(SALT))
    # do signing stuff
    return signature

How could I fix this? Is there a proper standard way to do this?

Asked By: Gh05d

||

Answers:

Try this instead:

SALT = "random string";
def sign(file):
    with open(private_key_path, 'rb') as f:
        key = f.read()
    hash_ = SHA256.new(file.read())
    hash_.update(SALT.encode())
    # do signing stuff
    return signature

According to the official hashlib documentation:

hash.update(data) updates the hash object with the bytes-like object (data).

This means that SHA256.new() actually creates a python object, and .update() is a method of this python object which updates the object’s property. It doesn’t return anything, and hence nothing will be stored in the hash variable of your 2nd code.

For more information, please take a look at this answer.

Answered By: SmartOinker
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.