2
\$\begingroup\$

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?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Oct 11, 2014 at 9:33
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

You can actually refactor most of the code into a separate function:

static function encryptdecrypt($text)
{
 $td = mcrypt_module_open(self::CIPHER, "", self::MODE, "");
 mcrypt_generic_init($td, self::KEY, 0);
 $text = mcrypt_generic($td, $text);
 mcrypt_generic_deinit($td);
 mcrypt_module_close($td);
 return $text;
}
static function encrypt($plaintext)
{
 return base64_encode(encryptdecrypt($plaintext));
}
static function decrypt($ciphertext)
{
 return encryptdecrypt(base64_decode($ciphertext));
}
answered Oct 11, 2014 at 13:48
\$\endgroup\$
2
  • \$\begingroup\$ Nice try. But for decrypt, it uses the function mdecrypt_generic instead of mcrypt_generic. But I get your idea. Thanks! \$\endgroup\$ Commented Oct 12, 2014 at 2:34
  • \$\begingroup\$ @QuestionOverflow: Oh, I didn't spot that difference. You could send a flag into the function for which function to call. \$\endgroup\$ Commented Oct 12, 2014 at 2:53

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.