Wednesday, July 10, 2013

CakePHP: Using rand() to Build a Stream Cipher

The following function can be found in the CakePHP framework. It's marked as deprecated, and it's going to be removed in a future version, but it's pretty bad:

  public static function cipher($text, $key) {  
      if (empty($key)) {  
           trigger_error(__d('cake_dev', 'You cannot use an empty key for Security::cipher()'), E_USER_WARNING);  
           return '';  
      }  
      srand(Configure::read('Security.cipherSeed'));  
      $out = '';  
      $keyLength = strlen($key);  
      for ($i = 0, $textLength = strlen($text); $i < $textLength; $i++) {  
           $j = ord(substr($key, $i % $keyLength, 1));  
           while ($j--) {  
                rand(0, 255);  
           }  
           $mask = rand(0, 255);  
           $out .= chr(ord(substr($text, $i, 1)) ^ $mask);  
      }  
      srand();  
      return $out;  
 }  

Lesson learned:
  • Don't invent your own cipher. Use a well-known cipher that has been tested and analyzed extensively by experts, like AES, Serpent, or Twofish.

No comments:

Post a Comment