note 108437 deleted from book.mcrypt by danbrown

From: Date: Thu, 10 May 2012 16:59:40 +0000
Subject: note 108437 deleted from book.mcrypt by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-187630@lists.php.net to get a copy of this message
Note Submitter: scottwmcgregor at gmail dot com ---- I had some trouble getting mcrypt to play nicely with MySQL's AES_ENCRYPT & AES_DECRYPT methods, so here are two functions I pieced together which interoperate therewith: <?php /** * A class that provides AES 128-bit electronic codebook encryption and * decryption of data. This class was specifically created to allow php to * communicate with MySQL's AES_ENCRYPT and AES_DECRYPT methods, which seem to * be rather under-documented. * @author scottwmcgregor at gmail */ class AesEcb128 { /** * Provides AES 128-bit key electronic codebook decryption of encrypted text * that has also been encoded in base64 given a key. * @author Tom Russ * @author scottwmcgregor @ gmail * @param string $key the encryption key to be used * @param string $encrypted_text the text to be decrypted * @return string $decrypted the decrypted string (trimmed) */ static function decrypt($key, $encrypted_text) { $decoded = base64_decode($encrypted_text); $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '',MCRYPT_MODE_ECB, ''); // The iv is ignored in ecb mode, this is here to suppress warnings from php $iv = pack("a" . mcrypt_enc_get_iv_size($td), NULL); mcrypt_generic_init($td, $key, $iv); $decrypted = mdecrypt_generic($td, $decoded); mcrypt_generic_deinit($td); mcrypt_module_close($td); return rtrim($decrypted); //remove padding } /** * Encrypt in PHP using AES 128-bit encryption and electronic codebook * @author scottwmcgregor @ gmail * @param string $key * @param string $plain_text * @return string $encoded */ static function encrypt($key, $plain_text) { $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '',MCRYPT_MODE_ECB, ''); // The iv is ignored in ecb mode, this is here to suppress warnings from php $iv = pack("a" . mcrypt_enc_get_iv_size($td), NULL); mcrypt_generic_init($td, $key, $iv); $blocksize = mcrypt_enc_get_block_size($td); $plain_text = self::pkcs5_pad($plain_text, $blocksize); $encrypted = mcrypt_generic($td, $plain_text); $encoded = base64_encode($encrypted); mcrypt_generic_deinit($td); mcrypt_module_close($td); return $encoded; } /** * Borrowed from http://www.php.net/manual/en/ref.mcrypt.php#69782 * @param string $text * @param int $blocksize * @return string */ static function pkcs5_pad ($text, $blocksize) { $pad = $blocksize - (strlen($text) % $blocksize); return $text . str_repeat(chr($pad), $pad); } } ?>

« previous php.notes (#187630) next »