How to serialize a Hash object from Hashlib for Socket submission?

Asked

Viewed 41 times

-2

How is it possible to serialize an object of the type _hashlib.HASH , so that it is suitable for sending via sockets (sendall() and send()) ?

With the pickle is made:

hashed_Message = hashlib.sha256(message.encode('utf-8'))
    
serializedHashed_Message = pickle.dumps(hashed_Message)
    
conn.sendall(serializedHashed_Message)

But in doing so happens the following Exception:

Typeerror: can’t pickle _hashlib.HASH Objects

And when trying to send the object directly the sending function requires bytes. How to handle?

1 answer

1


You can use the function hash.Digest() to get the bytes of the hash and pass to conn.sendall, without needing the pickle.

hashed_Message = hashlib.sha256(message.encode('utf-8'))
    
serializedHashed_Message = hashed_Message.digest()
    
conn.sendall(serializedHashed_Message)
  • Thankful, it was one of the ways I was thinking of doing it, but wanted it the other way, because there are other objects that are not so simply serialized.

  • If that hash is a property of an object, you can try using the __setstate__ and __getstate__ pickle to convert to bytes when serialize the object.

Browser other questions tagged

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