How do I decrypt using hashlib in python?

Kamilski81 picture Kamilski81 · Apr 11, 2013 · Viewed 97.7k times · Source

I know how to encrypt:

encrypted = hashlib.sha256('1234').hexdigest()

But I am not sure, how to decrypt this?

decrypted = decrypt(encrypted)

Answer

Anil Vaitla picture Anil Vaitla · Apr 11, 2013

The point of a hash like sha256 is that it is supposed to be a one way function (although the existence of true one way functions is still an open question, see http://en.wikipedia.org/wiki/One-way_function).

Note http://en.wikipedia.org/wiki/Cryptographic_hash_function:

The ideal cryptographic hash function has four main properties:

    1. it is easy to compute the hash value for any given message
    1. it is infeasible to generate a message that has a given hash
    1. it is infeasible to modify a message without changing the hash
    1. it is infeasible to find two different messages with the same hash.

If you could reverse it then you'd be breaking rule 2. These rules allow one to tell another party that they have some information (such as a password), without revealing the information. For example, see wikipedia: http://en.wikipedia.org/wiki/Cryptographic_hash_function#Illustration

If you need invertibility see Simple way to encode a string according to a password?, you can use something weak like Vignere, but there is also an example using PyCrypto:

from Crypto.Cipher import AES
import base64

cipher = AES.new(secret_key,AES.MODE_ECB) # never use ECB in strong systems obviously
encoded = base64.b64encode(cipher.encrypt(msg_text))
# ...
decoded = cipher.decrypt(baes64.b64decode(msg_text))

If you want a reversible hash function, see Reversible hash function?