I wish to convert a string to md5 and to base64. Here's what I achieved so far:
base64开发者_如何学编程.urlsafe_b64encode("text..." + Var1 + "text..." +
hashlib.md5(Var2).hexdigest() + "text...")
Python raises a TypeError which says: Unicode objects must be encoded before hashing
.
Edit: This is what I have now:
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"
Var1
and Var2
are strings (unicode) but the md5()
and urlsafe_b64encode()
functions require plain old bytes as input.
You must convert Var1
and Var2
to a sequence of bytes. To do this, you need to tell Python how to encode the string as a sequence of bytes. To encode them as UTF-8, you could do this:
b1 = Var1.encode('utf-8')
b2 = Var2.encode('utf-8')
You could then pass these byte-strings to the functions:
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 ...)
精彩评论