tags:

views:

91

answers:

1

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"
+1  A: 

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 ...)
David Underhill
I invoked the function bytes() on Var1 and Var2 but it didn't help. Gave a TypeError: `String argument without an encoding`.Edit: Now, when using the method encode(), I get the error: `Can't convert 'bytes' object to str implicitly`
Dor
If you want to use `bytes()`, you'll need to specify how the string is to be encoded. For example: `b1 = bytes(Var1, 'utf-8')` or `b1 = bytes(Var2, 'ascii')`.
David Underhill
Please see my edit.
Dor
Yes, I edit my question, Thanks.
Dor
I've updated the answer - the input to `urlsafe_b64encode()` needs to be bytes, so you have to convert the `"text..."` strings to bytes as well. Also, use the `digest()` method vice `hexdigest()` method to get the md5 sum as bytes.
David Underhill
Thx, it worked.
Dor
You're welcome :)
David Underhill