Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

drop 0 from md5() PHP if byte representation is less than 0x10

Tags:

php

md5

Using md5() function in PHP directly gives me the String. What I want to do before saving the string in the database is remove zeroes 0 if any in the byte representation of that hex and that byte representation is < 0x10 and then save the string in the database.

How can I do this in PHP?

MD5 - PHP - Raw Value - catch12 - 214423105677f2375487b4c6880c12ae - This is what I get now. Below is the value that I want the PHP to save in the database.

MD5 - Raw Value - catch12 - 214423105677f2375487b4c688c12ae

Wondering why? The MD5 code I have in my Android App for Login and Signup I did not append zeroes for the condition if ((b & 0xFF) < 0x10) hex.append("0"); Works fine. But the Forgot Password functionality in the site is PHP which is when the mismatch happens if the user resets password. JAVA code below.

byte raw[] = md.digest();  
StringBuffer hexString = new StringBuffer();
for (int i=0; i<raw.length; i++)
hexString.append(Integer.toHexString(0xFF & raw[i]));
v_password = hexString.toString();

Any help on the PHP side so that the mismatch does not happen would be very very helpful. I can't change the App code because that would create problems for existing users.

Thank you.

like image 946
Aakash Avatar asked Nov 06 '22 00:11

Aakash


1 Answers

Pass the "normal" MD5 hash to this function. It will parse it into the individual byte pairs and strip leading zeros.

EDIT: Fixed a typo

function convertMD5($md5)
{
    $bytearr = str_split($md5, 2);
    $ret = '';

    foreach ($bytearr as $byte)
        $ret .= ($byte[0] == '0') ? str_replace('0', '', $byte) : $byte;

    return $ret;
}

Alternatively, if you don't want zero-bytes completely stripped (if you want 0x00 to be '0'), use this version:

function convertMD5($md5)
{
    $bytearr = str_split($md5, 2);
    $ret = '';

    foreach ($bytearr as $byte)
        $ret .= ($byte[0] == '0') ? $byte[1] : $byte;

    return $ret;
}
like image 74
Unsigned Avatar answered Nov 12 '22 12:11

Unsigned