title: "MD5 decrypt" php function to MySQL stored function
body: <p>I'm trying to fix things on a PHP site. There is a pair of PHP functions:</p>
  
  <pre><code>function get_rnd_iv($iv_len) {
          $iv = '';
          while ($iv_len-- &gt; 0) {
                  $iv .= chr(mt_rand() &amp; 0xff);
          }
          return $iv;
  }
  function md5_encrypt($plain_text, $password, $iv_len = 16) {
          $plain_text .= "\x13";
          $n = strlen($plain_text);
          if ($n % 16) $plain_text .= str_repeat("\0", 16 - ($n % 16));
          $i = 0;
          $enc_text = get_rnd_iv($iv_len);
          $iv = substr($password ^ $enc_text, 0, 512);
          while ($i &lt; $n) {
                  $block = substr($plain_text, $i, 16) ^ pack('H*', md5($iv));
                  $enc_text .= $block;
                  $iv = substr($block . $iv, 0, 512) ^ $password;
                  $i += 16;
          }
          return base64_encode($enc_text);
  }
  function md5_decrypt($enc_text, $password, $iv_len = 16) {
          $enc_text = base64_decode($enc_text);
          $n = strlen($enc_text);
          $i = $iv_len;
          $plain_text = '';
          $iv = substr($password ^ substr($enc_text, 0, $iv_len), 0, 512);
          while ($i &lt; $n) {
                  $block = substr($enc_text, $i, 16);
                  $plain_text .= $block ^ pack('H*', md5($iv));
                  $iv = substr($block . $iv, 0, 512) ^ $password;
                  $i += 16;
          }
          return preg_replace('/\\x13\\x00*$/', '', $plain_text);
  }
  </code></pre>
  
  <p>They are used to encrypt the IP addresses of users in the database.
  The $password parameter is stored in a php config file (so only dumping the sql will not give you the IP-s even when you know these functions).</p>
  
  <p>I'm still puzzled over them as MD5 is clearly hashing and only things like bruteforcing can reverse it.</p>
  
  <p>Can someone with more php experience explain, how this decryption works? The encrypted text is not a simple MD5 so I might have to understand what is happening there.</p>
  
  <p>Anyway I'm trying to write a mysql stored function doing the decryption, because I want to join an other table by the IP-s (a table containing IP ranges for countries), and only return the country codes in the query.</p>
  
  <p>The problems are: I have never written a MySQL function. How do I make a while cycle? there are functions like pack, and preg_replace which are not built in in MySQL, do I have to implement them too somehow?</p>
  
  <p>Any help would be appreciated (ranging from hints to the full function)!</p>
  
  <p>Comments like "MD5 cannot be decrypted it's hashing!" will not be appreciated.</p>