【问题标题】:Decode string using python || SHA256使用 python 解码字符串 || SHA256
【发布时间】:2020-05-04 19:14:28
【问题描述】:

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

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

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

【问题讨论】:

  • SHA256 不是加密,它是一个哈希。哈希是单向的,你不能倒退
  • @Sami,有没有双向哈希?
  • 不,根据定义,哈希是单向的
  • @SamiKuhmonen,那我最好使用一些加密算法,比如AES?我说的对吗?
  • 如果你想回去,那么是的,你需要一个加密算法来代替

标签: python-3.x md5 sha256 hashlib


【解决方案1】:

你不能用哈希来做到这一点

您应该使用密码,例如 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)

这应该返回 https://booking.com

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

例如:

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


"".join("{:02x}".format(c) for c in cipherstring)
表示每个字符都以十六进制格式编码,并且字符列表与分隔符“”连接(它正在转换为字符串)

【讨论】:

  • encrypt("booking.com", cipher1) 给出了一些带有很多反斜杠的奇怪的很长的字符串,有没有办法转换成十六进制字符串?
  • 哇,太棒了!非常感谢,@Kumpelinus。
猜你喜欢
  • 2018-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-29
  • 2011-10-18
  • 2017-11-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多