title: Encrypt/decrypt with XOR in PHP
body: <p>I am studying encryption. And I got a problem like this:</p>
  
  <p>After I XOR plaintext with a key, I get a crypt, "010e010c15061b4117030f54060e54040e0642181b17", as hex type. If I want to get plaintext from this crypt, what should I do in PHP?</p>
  
  <p>I tried convert it to string/int and after that take them to XOR with the key (three letters). But it doesn't work.</p>
  
  <p>This is the code:</p>
  
  <pre><code>function xor_this($string) {
  
      // Let's define our key here
      $key = 'fpt';
  
      // Our plaintext/ciphertext
      $text = $string;
  
      // Our output text
      $outText = '';
  
      // Iterate through each character
      for($i=0; $i&lt;strlen($text); )
      {
          for($j=0; $j&lt;strlen($key); $j++,$i++)
          {
              $outText .= ($text[$i] ^ $key[$j]);
              //echo 'i=' . $i . ', ' . 'j=' . $j . ', ' . $outText{$i} . '&lt;br /&gt;'; // For debugging
          }
      }
      return $outText;
  }
  
  function strToHex($string)
  {
      $hex = '';
      for ($i=0; $i &lt; strlen($string); $i++)
      {
          $hex .= dechex(ord($string[$i]));
      }
      return $hex;
  }
  
  function hexToStr($hex)
  {
      $string = '';
      for ($i=0; $i &lt; strlen($hex)-1; $i+=2)
      {
          $string .= chr(hexdec($hex[$i].$hex[$i+1]));
      }
      return $string;
  }
  
  $a = "This is the test";
  $b = xor_this($a);
  echo xor_this($b), '-------------';
  //
  $c = strToHex($b);
  $e = xor_this($c);
  echo $e, '++++++++';
  //
  $d = hexToStr($c);
  $f = xor_this($d);
  echo $f, '=================';
  </code></pre>
  
  <p>And this is the result:</p>
  
  <blockquote>
    <p>This is the test-------------</p>
    
    <p>PHP Notice:  Uninitialized string offset: 29 in C:\
    Users\Administrator\Desktop\test.php on line 210 PHP Stack trace: PHP
    1. {main}() C:\Users\Administrator\Desktop\test.php:0 PHP   2. xor_this() C:\Users\Administrator\Desktop\test.php:239</p>
    
    <p>Notice: Uninitialized string offset: 29 in
    C:\Users\Administrator\Desktop\test.p hp on line 210</p>
    
    <p>Call Stack:
        0.0005     674280   1. {main}() C:\Users\Administrator\Desktop\test.php:0
        0.0022     674848   2. xor_this() C:\Users\Administrator\Desktop\test.php:23 9</p>
    
    <p>UBE^A►WEAVA►WEAV@◄WEARAFWECWB++++++++</p>
    
    <p>This is zs$fs☺=================</p>
  </blockquote>
  
  <p>Why? The "UBE^A►WEAVA►WEAV@◄WEARAFWECWB++++++++" is the result, which I got trouble in my real work.</p>