Pablo
Pablo

Reputation: 10640

How to encode md5 sum to base64 in Javascript

I have a login web form, user writes his password and I must encrypt it on MD5 and the sum to base 64. I'm doing like this with CryptoJS:

var hash = CryptoJS.MD5(cred.password); // password is `password`
cred.password = hash.toString(CryptoJS.enc.Base64); // X03MO1qnZdYdgyfeuILPmQ==  --  IT IS OK!

This works fine. Then I must convert the following string to MD5 and Base64 too:

var digest = "john.doe,"+hash.toString()+",QCiTzbXCAYA3AvDgYN3MuBwY/1i89q6TfW7aVS1Av1c=";

again I do:

var hash1 = CryptoJS.MD5(digest);
digestResult = hash1.toString(CryptoJS.enc.Base64);

It returns i4a9M2b6l+yBZLHc3bXWMA== but the expected by the server for this conbination is 6R1HZqYJFfRQUA0L/hqCEA==

I guess Crypto is not working for a base64/md5 inside the string to convert?

I dont get why it returns bad

Upvotes: 0

Views: 7669

Answers (1)

deamentiaemundi
deamentiaemundi

Reputation: 5525

The function CryptoJS.MD5(cred.password) returns a typedArray, not a string. It has a toString function which returns the common hexadecimal representation. All of that won't fit very well together. You'll need to probe the client/server strings to see what one sends and the other accepts but you should use the hexadecimal string representation all the way up to the final base64 encoding, mixing them is not very healthy. EDIT after some comments given by the OP

var hash = CryptoJS.MD5(cred.password); // password is `password`
// "hash" contains a typed array, needs to be base64
hash = hash.toString(CryptoJS.enc.Base64); // X01jw2Jap2XWHYMn3riCz5k=
var digest = "john.doe,"+hash+",QCiTzbXCAYA3AvDgYN3MuBwY/1i89q6TfW7aVS1Av1c=";
digest = CryptoJS.MD5(digest);
digest = digest.toString(CryptoJS.enc.Base64); // jH+dH56sKswaDDfeCzDY0A==
// send "digest" to server

Cannot go further without knowledge of server-side code.

Upvotes: 4

Related Questions