The following is a very simple implementation of an Encryption
class using mcrypt whereby the functions encrypt
and decrypt
are called statically by a PHP script on GET and on POST respectively:
class Encryption
{
const CIPHER...
static function encrypt($plaintext)
{
$td = mcrypt_module_open(self::CIPHER, "", self::MODE, ""); # <= move this outside?
mcrypt_generic_init($td, self::KEY, 0);
$ciphertext = mcrypt_generic($td, $plaintext);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return base64_encode($ciphertext);
}
static function decrypt($ciphertext)
{
$td = mcrypt_module_open(self::CIPHER, "", self::MODE, ""); # <= repeated
mcrypt_generic_init($td, self::KEY, 0);
$plaintext = mdecrypt_generic($td, base64_decode($ciphertext));
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $plaintext;
}
}
Ignoring other aspects of this stripped down code, what I want to achieve is to reduce code duplication by perhaps moving $td = mcrypt_module_open(self::CIPHER, "", self::MODE, "");
outside. Can this be done without combining the two methods or is what I have already at the optimum?