note 63484 deleted from function.mcrypt-module-open by bjori

From: Date: Wed, 22 Mar 2006 20:45:38 +0000
Subject: note 63484 deleted from function.mcrypt-module-open by bjori
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-106370@lists.php.net to get a copy of this message
Note Submitter: Reason: bad code ---- I needed to have a way of encrypting and decrypting information in a database, and the mcrypt library seemed like the best way to do that. After reading the documentation and examples I created two functions. One was to encrypt data and the other was to decrypt data. Here is basically what I wrote at first: function myencrypt($data, $key) { $td = mcrypt_module_open('tripledes', '', 'ecb', ''); $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_DEV_RANDOM); $ks = mcrypt_enc_get_key_size($td); mcrypt_generic_init($td, $key, $iv); $encrypted = mcrypt_generic($td, $data); mcrypt_generic_deinit($td); mcrypt_module_close($td); return base64_encode($encrypted); } function mydecrypt($encrypted_data, $key) { $td = mcrypt_module_open('tripledes', '', 'ecb', ''); $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_DEV_RANDOM); $ks = mcrypt_enc_get_key_size($td); mcrypt_generic_init($td, $key, $iv); $decrypted = mdecrypt_generic($td, base64_decode( $encrypted_data )); mcrypt_generic_deinit($td); mcrypt_module_close($td); return $decrypted; } After writing the functions I began to test them. These functions would run well for about the first 50-100 times, and then pause for a while (I imagine that the program was blocked waiting for a resource) and then run 50-100 more and pause again. I think the problem is that the function was calling mcrypt_module_open each time it ran and that must make a system call to allocate a file handle, or some kind of resource handle. To fix this I replaced the functions with the following: $__td = mcrypt_module_open('tripledes', '', 'ecb', ''); $__iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($__td), MCRYPT_DEV_RANDOM); $__ks = mcrypt_enc_get_key_size($__td); function myencrypt($data, $key) { global $__td, $__iv, $__ks; mcrypt_generic_init($__td, $key, $__iv); $encrypted = mcrypt_generic($__td, $data); mcrypt_generic_deinit($__td); return base64_encode($encrypted); } function mydecrypt($encrypted_data, $key) { global $__td, $__iv, $__ks; mcrypt_generic_init($__td, $key, $__iv); $decrypted = mdecrypt_generic($__td, base64_decode($encrypted_data)); mcrypt_generic_deinit($__td); return $decrypted; } Since it uses a global handle to the mcrypt module, it never has to wait for the system to return a handle. Benchmarked these new functions with a test script that did 10000 encrypts and decrypts and it ran perfectly. For those of you that don't like to allocate something and never de-allocate it, rest assured that PHP will clean it up. One of the beauties of PHP.

« previous php.notes (#106370) next »