/** * Encrypts plaintext using Blowfish with the given key. * * @param string $plaintext the string to encrypt * @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 encrypted string. It is recommended you base64encode this for storage. * @author Matt Harris **/ public function encrypt($plaintext, $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; } $ciphertext = ''; $fish = new Blowfish($key, $mode, $padding, $iv); $block =& $fish->blockSize; $paded = $fish->_pad($plaintext); $len = strlen($paded); # encrypt in 1 byte intervals for ($i = 0; $i < $len; $i += $block) { if ($mode == Blowfish::BLOWFISH_MODE_CBC) { $chain = $i == 0 ? $fish->IV : substr($ciphertext, $i - $block, $block); list(, $xL, $xR) = unpack('N2', substr($paded, $i, $block) ^ $chain); } else { list(, $xL, $xR) = unpack('N2', substr($paded, $i, $block)); } $fish->_encipher($xL, $xR); $ciphertext .= pack('N2', $xL, $xR); } unset($fish); return $ciphertext; }