使用 python 解码字符串 || SHA256

Decode string using python || SHA256

我目前正在 python 中使用 hashlib 库来使用 SHA256 加密 URL。以下是代码。

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

现在,我想解密并取回 url。谁能告诉我怎么做?

你不能用散列来做到这一点

你应该使用密码,例如 AES Cipher


示例:

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)

这个应该returnhttps://booking.com.

编辑: 如果你想要一个十六进制格式的编码字符串,你可以结合使用 join and the format 命令。

例如:

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