Example #1
0
 /**
  * Decrypts the ciphertext using Blowfish with the given key.
  *
  * @param string $ciphertext the encrypted string
  * @param string $key the encryption key
  * @param int $mode one of BLOWFISH_MODE_CBC, BLOWFISH_MODE_EBC. BLOWFISH_MODE_CBC is recommened
  * @param int $padding one of BLOWFISH_PADDING_NONE, BLOWFISH_PADDING_RFC, BLOWFISH_PADDING_ZERO. BLOWFISH_PADDING_RFC is recommened
  * @param int $iv the initialisation vector. Required when using CBC mode.
  * @return string Returns the plaintext string.
  * @author Matt Harris
  **/
 public function decrypt($ciphertext, $key, $mode = Blowfish::BLOWFISH_MODE_CBC, $padding = Blowfish::BLOWFISH_PADDING_RFC, $iv = NULL)
 {
     if ($mode == Blowfish::BLOWFISH_MODE_CBC and empty($iv)) {
         throw new Exception('CBC Mode requires an IV key');
         return;
     }
     $plaintext = '';
     $fish = new Blowfish($key, $mode, $padding, $iv);
     $block =& $fish->blockSize;
     $len = strlen($ciphertext);
     # encrypt in 1 byte intervals
     for ($i = 0; $i < $len; $i += $block) {
         list(, $xL, $xR) = unpack('N2', substr($ciphertext, $i, $block));
         $fish->_decipher($xL, $xR);
         if ($mode == Blowfish::BLOWFISH_MODE_CBC) {
             $chain = $i == 0 ? $fish->IV : substr($ciphertext, $i - $block, $block);
             $plaintext .= pack('N2', $xL, $xR) ^ $chain;
         } else {
             $plaintext .= pack('N2', $xL, $xR);
         }
     }
     $plaintext = $fish->_unpad($plaintext);
     unset($fish);
     return $plaintext;
 }