Question

I know how to encrypt:

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

But I am not sure, how to decrypt this?

decrypted = decrypt(encrypted)
Was it helpful?

Solution

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?

OTHER TIPS

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.

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.

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 !

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.

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()))

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 :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top