开发者

How to base-64 encode the md5 sum of a string?

开发者 https://www.devze.com 2023-01-08 06:11 出处:网络
I wish to convert a string to md5 and to base64. Here\'s what I achieved so far: base64开发者_如何学编程.urlsafe_b64encode(\"text...\" + Var1 + \"text...\" +

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 ...)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号