Tech4Wilco
Tech4Wilco

Reputation: 6818

PHP pack/unpack error

I have to convert an old "encrypted" data to a proper encryption algorithm from an old system. I have this code:

 function unpackString($s,$l){
      $tmp=unpack('c'.$l,$s);
      $return=NULL;
      foreach($tmp as $v){
          if($v>0){
              $return.=chr($v);
          }
      }
      return $return;
  }
  function packString($s,$l){
      $return=NULL;
      for($i=0;$i<$l;$i++){
          $return.=pack('c',ord(substr($s,$i,1)));
      }
      return $return;
  }

  $string='StackOverflow Is AWESOME';
  $l=strlen($string);

  $encoded=packString(base64_encode($string),$l);
  $decoded=base64_decode(unpackString($encoded,$l));


  echo "\n".$decoded."\n";

Why the output shows StackOverflow Is A and not StackOverflow Is AWESOME

Upvotes: 3

Views: 833

Answers (1)

Marc B
Marc B

Reputation: 360782

base64 encoding expands the size of a string by about 33%. You're passing in the length of the ORIGINAL string, not the base64 encoded one:

StackOverflow Is AWESOME  - 24 chars plaintext
U3RhY2tPdmVyZmxvdyBJcyBBV0VTT01F - 32 chars base64 encoded

So you're chopping off 8 characters, leaving you with

U3RhY2tPdmVyZmxvdyBJcyBB

which decodes to

StackOverflow Is A

Upvotes: 12

Related Questions