开发者

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

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 zer开发者_Python百科oes 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.


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;
}


$md5 = md5('catch12');
$new_md5 = '';
for ($i = 0; $i < 32; $i += 2)
{
  if ($md5[$i] != '0') $new_md5 .= $md5[$i];
  $new_md5 .= $md5[$i+1];
}

echo $new_md5;


To strip leading zeros (00->0, 0a->a, 10->10)

function stripZeros($md5hex) {
  $res =''; $t = str_split($md5hex, 2);
  foreach($t as $pair) $res .= dechex(hexdec($pair));
  return $res;  
  }

To strip leading zeros & zero bytes (00->nothing, 0a->a, 10->10)

function stripZeros($md5hex) {
  $res =''; $t = str_split($md5hex, 2);
  foreach($t as $pair)  {
    $b = dechex(hexdec($pair));
    if ($b!=0) $res .= $b;
    }
  return $res;  
  }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜