Search code examples
python-3.xmd5sha256hashlib

Decode string using python || SHA256


I am currently using hashlib library in python to encrypt a URL using SHA256. Following is the code.

import hashlib
url='https://booking.com'
hs = hashlib.sha256(url.encode('utf-8')).hexdigest()
print(hs) # 037c89f2570ac1cff92d67643f570bec93ebea7f0222e105616590a9673be21f

Now, I want to decrypt and get back the url. Can someone tell me how to do this?


Solution

  • You can't do that with a hash

    You should use a Cipher for example the AES Cipher


    Example:

    from Crypto.Cipher import AES
    
    
    def resize_length(string):
        #resizes the String to a size divisible by 16 (needed for this Cipher)
        return string.rjust((len(string) // 16 + 1) * 16)
    
    def encrypt(url, cipher):
        # Converts the string to bytes and encodes them with your Cipher
        return cipher.encrypt(resize_length(url).encode())
    
    def decrypt(text, cipher):
        # Converts the string to bytes and decodes them with your Cipher
        return cipher.decrypt(text).decode().lstrip()
    
    
    # It is important to use 2 ciphers with the same information, else the system breaks (at least for me)
    # Define the Cipher with your data (Encryption Key and IV)
    cipher1 = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
    cipher2 = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
    decrypt(encrypt("https://booking.com", cipher1), cipher2)
    

    This should return https://booking.com.

    Edit: If you want to have an encoded string in the hex format you could use the join and the format command in combination.

    For exmple:

    #For encoding
    cipherstring = cipher.encrypt(resize_length(url).encode())
    cipherstring = "".join("{:02x}".format(c) for c in cipherstring)
    
    #For decoding
    text = bytes.fromhex(text)
    original_url = cipher.decrypt(text).decode().lstrip()
    

    The
    "".join("{:02x}".format(c) for c in cipherstring)
    means every character gets encoded in hexadecimal format and the list of characters gets joined with the seperator "" (it is beeing converted to a string)