I would like to generate the mysql-password hash from js.
I know the method with php functions,
$p = "example";
echo("$p<br>");
$p2= sha1($p,true);
echo("$p2<br>"); //ĂI')s~űvŠ-Ëo?
$result = sha1($p2);
echo("$result<br>"); //*57237bb49761f29ab9724ba084e811d70c12393d - this is the same as password("example") in mysql
and I’m trying to do this in javascript.
here is located the sha1 function:
http://pajhome.org.uk/crypt/md5/sha1.html
this is the hex2bin function I use to give the same result as sha1(“”,true);
function hex2bin(hex)
{
var bytes = [], str;
for(var i=0; i< hex.length-1; i+=2)
bytes.push(parseInt(hex.substr(i, 2), 16));
return String.fromCharCode.apply(String, bytes);
}
but at the last step it does not work. What can be the problem?
var p = "example";
console.log(p);
var p2 = hex2bin(hex_sha1(p));
console.log(p); //ÃI')s~ûv©-Ëo? - SEEMS OK
var result = hex_sha1(p2);
console.log(result); //9a5355dce26b1adfa0bdbe9f2b2a6e5ae58e5c9d WRONG
So, in the example above, you are invoking:
hex_sha1(hex2bin(hex_sha1(string))). Are you sure that is correct? Why would you needhex_sha1twice?Few month ago, I needed SHA1 in my JS and found this: http://phpjs.org/functions/sha1:512
… and it worked pretty ok 😉
The solution (partly):
Well, as you suggested, the main problem was charset encoding. It seems that
MySQLdoes not encode any data prior to hashing it. This does not represent problem when dealing it with hex data, however,MySQL‘sUNHEX(hex2binin JS) returns some unreadable chars and if we encode the result usingUTF8that’s where all breaks apart.When I edited JS’s SHA1 not to encode data to
UTF8at line (I only commented the line):everything seemed ok. However, as soon as I supplied some
UTF8chars to input (such as Central European charsčćžšđ) it started failing again.So, bottom line, if you disable
UTF8inJSsSHA1function and do not supplyUTF8chars on input it works fine.I’m sure there is a solution to this such as
JSfunction that will decodeUTF8input so, JS could hash it properly.