Reputation: 87
I want to encode some strings with php and javascript... My Php code:
<?php
$number = '8793';
$hash = md5($number);
$hash = sha1($hash);
$hash = md5($hash);
$hash = md5($hash);
$hash = sha1($hash);
$hash = sha1($hash);
$hash = md5($hash);
$hash = sha1($hash);
echo $hash;
?>
It Returns me this: 4dcfc4eb41e2a44dce5d7180f08a5217f1c6811c
And here is my javascript code:
<div id="messages"></div>
<script type="text/javascript" src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js"></script>
<script type="text/javascript" src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/md5.js"></script>
<script type="text/javascript">
function md5(string)
{
return CryptoJS.MD5(string);
}
function sha1(string)
{
return CryptoJS.SHA1(string);
}
function encode(string)
{
var number = string;
var hash = md5(number);
var hash = sha1(hash);
var hash = md5(hash);
var hash = md5(hash);
var hash = sha1(hash);
var hash = sha1(hash);
var hash = md5(hash);
var hash = sha1(hash);
return hash;
}
var text = '8793';
document.getElementById("messages").innerHTML = encode('8793');
</script>
But it returns me 8cdd439c88aa2276bdc1ac7cb58b7c403fb6e929 How can I fix it?
Upvotes: 1
Views: 326
Reputation: 18491
As well as Theraot solution you can try something like this:
http://jsfiddle.net/3ukb41gp/1/
function encode(str)
{
var number = str;
var hash = md5(number).toString();
hash = sha1(hash).toString();
hash = md5(hash).toString();
hash = md5(hash).toString();
hash = sha1(hash).toString();
hash = sha1(hash).toString();
hash = md5(hash).toString();
hash = sha1(hash).toString();
return hash;
}
Upvotes: 1
Reputation: 40170
In your javascript code, when you do MD5 and SHA1 it returns an object that has the actual code, instead of an string with the hexadecimal representation. This means that the following operations are doing the hash over the numeric value instead of the string.
To fix it do a convertion to string in each step:
<div id="messages"></div>
<script type="text/javascript" src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js"></script>
<script type="text/javascript" src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/md5.js"></script>
<script type="text/javascript">
function md5(string)
{
return CryptoJS.MD5(string);
}
function sha1(string)
{
return CryptoJS.SHA1(string);
}
function encode(string)
{
var number = string;
var hash = md5(number);
var hash = sha1('' + hash); // <--- converting to string
var hash = md5('' + hash);
var hash = md5('' + hash);
var hash = sha1('' + hash);
var hash = sha1('' + hash);
var hash = md5('' + hash);
var hash = sha1('' + hash);
return hash;
}
var text = '8793';
document.getElementById("messages").innerHTML = encode('8793');
</script>
With this modification, Javascript will output 4dcfc4eb41e2a44dce5d7180f08a5217f1c6811c
.
Upvotes: 3