http://qs321.pair.com?node_id=1066456


in reply to port a function from php

Are you sure it's perl that's wrong? PHP is giving some weird results. I've added a print in both perl and php:

print "^:" . strlen($password ^ substr($enc_text, 0, $iv_len)) . "\n";

(s/strlen/length/ in perl of course), and the result in PHP is 4 instead of the expected 16. Adding a few more lines:

for ($x=0; $x<$iv_len; $x++) { printf("%02x ", ord(substr($enc_text,$x +,1))); } print "\n"; for ($x=0; $x<$iv_len; $x++) { printf("%02x ", ord(substr($password,$x +,1))); } print "\n"; for ($x=0; $x<$iv_len; $x++) { printf("%02x ", ord(substr($password,$x +,1))^ord(substr($enc_text,$x,1))); } print "\n";

shows what's going on. Output of those lines on both the perl and php versions shows:

5c 79 e1 71 1c cc ba 8e b7 46 aa 99 99 bc 56 d6 74 65 73 74 00 00 00 00 00 00 00 00 00 00 00 00 28 1c 92 05 1c cc ba 8e b7 46 aa 99 99 bc 56 d6

Looks like PHP is truncating the XOR when the shortest string run out, in this case your password, "test". Quick and dirty hack to make perl return the same result is:

sub md5_decrypt { my $iv_len = 16; my $enc_text = decode_base64(shift); my $password = shift; my $n = length($enc_text); my $i = $iv_len; my $plain_text; my $iv = substr($password ^ substr($enc_text,0,length($password)), + 0, 512); my $x; while ($i < $n) { my $block = substr($enc_text, $i, 16); $plain_text .= $block ^ pack('H*', md5_hex($iv)); $iv = substr($block . $iv, 0, length($password)) ^ $password; $i += 16; } #$plain_text =~ s/\x13\x00*$//; return $plain_text; }

But somehow I doubt that's actually the right thing to do.