26

I know how to encrypt:

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

But I am not sure, how to decrypt this?

decrypted = decrypt(encrypted)
6
  • 10
    That's not how hashing works. In general, the whole point of a hash is that it can't be undone. Hashing is not an encryption technique.
    – BrenBarn
    Commented Apr 11, 2013 at 19:16
  • wikipedia has a nice article about hashes Commented Apr 11, 2013 at 19:17
  • Just think about it. If you could "decrypt" a hash, which is very short, 32 bytes for SHA256, you would have ultimate compression method. But of course you can not, for any data that is longer than the hash, there are hash collisions, in other words different data which produce same hash (but with cryptographically secure hash like SHA256, you can't actually find or create collisions with current or foreseeable computers).
    – hyde
    Commented Apr 11, 2013 at 19:22
  • 1
    Why collisions exist with simple example: en.wikipedia.org/wiki/Pigeonhole_principle Commented Apr 11, 2013 at 19:23
  • Only way to get back the original string back from sha1 is to brute force. There is no decrypt function for any hash function. That is the whole point of hashing. Yet sha1(small string) can be brute forced to get back the original string. Commented Nov 28, 2014 at 4:39

7 Answers 7

35

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?

1
  • encrypt function says ValueError: Input strings must be a multiple of 16 in length Commented May 5, 2019 at 23:46
7

The short answer is you cannot 'decrypt' a hash; it is a one way function. There is a major difference between encrypting and hashing.

Hashing

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

Note: It is possible to 'BREAK' certain hashing algorithms, but this is not decrypting. You'll find more information in the links as well as other algorithms that are also supported by python

Encryption

and http://en.wikipedia.org/wiki/Encryption

Example

A useful example of hashing is storing passwords in a database whereas a useful example of encryption is sending your bank details to an online store to purchase something.

6

This is a valid question, maybe not posed correctly though.

OP, I think what you're trying to do is check a hashed value against an unhashed one?

hashed = hashlib.sha256('1234').hexdigest()
hashedstring = '1234' + ',' + hashed

now to check that hashed == original value. So parse out the piece before and after the comma. Hash 1234 and compare it to the value hashed.

def check_secure_val(h):
    commapos = h.find(",")
    val = h[0:commapos]
    hashval = h[commapos+1:-1]
    rehashval = hash_str(val)
    if rehashval == hashval:
        return val

where input h is a string of format "val,(HASHEDSTRING)"

and hash_str is a function that hashes.

3

The hashes are calculated using one way functions, i.e. it will give same output for a particular input but as it is only a one-way function, no matter what you do, you cannot decrypt it. One can try decrypting it by brute force, i.e calculating hashes of words from dictionary and comparing it with the hash you want to decrypt. To save the time of calculating the hashes of dictionary words, there are rainbow tables available online which contains hashes with the words.

read: http://en.wikipedia.org/wiki/Rainbow_table

You can also use online services for brute force decryption of a hash. there are plenty available and works well if the word you want to decrypt belongs to a dictionary.

3

Not-very-exact Analogy: Encryption is like someone wearing a disguise ... taking a Hash is like taking their fingerprints !

You can get the "original" person back by removing/reversing the disguise, but you cannot do that from a set of fingerprints !

2
  • 16
    really bad analogy Commented Jun 26, 2018 at 10:18
  • Yes,, @AkshayLAradhya as stated, it's not very exact. However, given the state of knowledge implied by the question, it conveys the degree of mismatch between expectation and reality. It's not intended to explain either hashing or encryption - just the level of difference between them. So it depends on what you were expecting; I am fairly exacting in my teaching standards, but I thought my "answer" would convey the issue.
    – MikeW
    Commented Jun 27, 2018 at 10:54
0

this might help?

import hashlib

l = ["riyad", "onni", "arman"]

def check_user(h):
    for i in l:
        if h == hashlib.md5(i.encode('utf-8')).hexdigest():
            return i


print(check_user(hashlib.md5(l[2].encode('utf-8')).hexdigest()))
0

I don't think you can decrypt it but what you can do is maybe take the range of guessed passwords for example in a for loop and put all of them "{password: hashed password" then check the hash and maybe you'll get it

so let's say you wanna crack a password that is in a CSV file and is between 0000-9999

the input csv file would be like :

name, hashed password

first we'll import csv and hashlib

import hashlib
import csv

now lets write a function that takes the hashed csv file and output csv file as arguments we'll make an empty string and an empty dict

def decryptor(input_file_name,output_file_name):
    # makes hashes
    clear_text = ""
    mydict = {}

now lets make a for loop in range of 0 and 9999 and we will encypt every number in that range

    for i in range(0, 10000):
        i = str(i).encode('utf-8') 
        encrypted = hashlib.sha256(i).hexdigest()
        mydict[i] = encrypted

now we'll just write them in csv file

    with open(input_file_name, 'r') as hash_file:
        # read's from csv file
        reader = csv.reader(hash_file)
        hash_dict = {}
        # reades every line of csv file
        for row in reader:
                hash_dict[row[0]] = row[1]

now we just need to check the hash we wanna decrypt with the hashes we already have and we'll get the unhashed password

    check_hash = []
    for i in list(mydict):
        text = "%s" % (mydict[i])
        check_hash.append(mydict[i])
    for i in list(hash_dict):
        if hash_dict[i] in check_hash:
            hashes = list(mydict.keys())[list(mydict.values()).index(hash_dict[i])]
            names = list(hash_dict.keys())[list(hash_dict.values()).index(hash_dict[i])],
            text = "%s,%s\n" % (names[0], hashes.decode('utf-8'))
            clear_text += text

now we write the out put to the output csv file

    with open(output_file_name, 'w') as passwords:
        passwords.write(clear_text)

and we'll just call the function

decryptor(<INPUT CSV>, <OUTPUT CSV NAME>)

This is my idea for you of cource you can't use this this is an idea hope it'll help :)

3
  • please added a descript answer and a simple code so you answer can be useful
    – xitas
    Commented Feb 19, 2022 at 11:39
  • 1
    As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Feb 19, 2022 at 11:39
  • hey sorry for not embedding any codes I'll do it right now Commented Feb 28, 2022 at 10:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.