Zathrus Writer
Zathrus Writer

Reputation: 4331

PHP adding up MD5 hashes?

I'm using + sign to add up 2 MD5 hashes like so:

md5('string1') + md5('string2')

now if I did this with strings, like so:

'string1' + 'string2'

...PHPp would give me 0 as a return value. However, with MD5 hashes, it always returns a numeric value, for which I cannot determine any origin.

Upvotes: 0

Views: 691

Answers (4)

Jovan Perovic
Jovan Perovic

Reputation: 20201

In PHP, + is numerical addition and . is string concatenation.

Also, md5(string) returns a string...

So:

$hashes = md5('string1') . md5('string2');

You probably want to numerically add hashes. Then you would need to convert the MD5 result to a number using hexdec().

Upvotes: -1

Kapil Sharma
Kapil Sharma

Reputation: 10427

Just to add, md5 function returns string value but md5 algorithm generates hexadecomal values.

Also remember PHP support some automated casting.

That is why php will give some values but you can't detect that value as even a single character change in string completely changes generated MD5 hash.

Still question is very interesting. Can you please let us know what are you trying to achieve by adding md5 hash?

Upvotes: 1

Jon
Jon

Reputation: 437854

You cannot add md5 hashes with + just as you cannot add any other kind of strings with +. The difference is expected and due to PHP's rules for string to number conversion. Contrast this:

'1string' + '2string'

with

'string1' + 'string2'

If numerically adding md5s gives you a result different from zero, it is because by chance the specific hashes you are adding start with one or more decimal digits.

There can be no legitimate reason to add two strings that do not represent decimal numbers, so don't do it.

Upvotes: 0

Mark Baker
Mark Baker

Reputation: 212522

It will depend on the hash values generated by your strings. When adding "string" values, PHP's behaviour (and it is well documented) is to take any leading numeric characters and treat them as an integer... if there are no leading numerics, then it will be treated as 0.

So

"1st String" + "2nd String" => 1 + 2 => 3

With your data

md5('string1') = '34b577be20fbc15477aadb9a08101ff9'
md5('string2') = '91c0c59c8f6fc9aa2dc99a89f2fd0ab5'

giving

34 + 91 => 125

Now why are you trying to add hash values?

Upvotes: 5

Related Questions