简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM