我希望将字符串转换为md5和base64。这是我到目前为止取得的成就:
base64.urlsafe_b64encode("text..." + Var1 + "text..." +
hashlib.md5(Var2).hexdigest() + "text...")
Python引发了一个TypeError,它说:Unicode objects must be encoded before hashing
。
编辑:这就是我现在所拥有的:
var1 = "hello"
var2 = "world"
b1 = var1.encode('utf-8')
b2 = var2.encode('utf-8')
result = "text" +
base64.urlsafe_b64encode("text" + b1 + "text" +
hashlib.md5(b2).hexdigest() + "text") +
"text"
答案 0 :(得分:2)
Var1
和Var2
是字符串(unicode),但md5()
和urlsafe_b64encode()
函数需要普通旧字节作为输入。
您必须将Var1
和Var2
转换为字节序列。为此,您需要告诉Python如何将字符串编码为字节序列。要将它们编码为UTF-8,您可以这样做:
b1 = Var1.encode('utf-8')
b2 = Var2.encode('utf-8')
然后,您可以将这些字节字符串传递给函数:
bmd5 = hashlib.md5(b2).digest() # get bytes instead of a string output
b3 = "text...".encode('utf-8') # need to encode these as bytes too
base64.urlsafe_b64encode(b3 + b1 ...)