Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mcrypt_generic vs mcrypt_encrypt

Tags:

php

mcrypt

Does anyone know the difference between mcrypt_generic and mcrypt_encrypt when it comes to encryption in PHP?

like image 250
Xerri Avatar asked May 05 '10 13:05

Xerri


1 Answers

mcrypt_encrypt() combines the functionality of several methods, whereas mcrypt_generic() must be called within a certain sequence of other mcrypt_* calls. You would use mcrypt_generic() if you needed the flexibility of the lower-level API, whereas mcrypt_encrypt() acts as a higher-level utility.

This example in the PHP documentation shows a good comparison between the two API approaches. It refers to mcrypt_ecb(), but for the purposes of this comparison you can consider it to be similar to mcrypt_encrypt().

From http://us.php.net/manual/en/mcrypt.examples.php

$key = "this is a secret key";
$input = "Let us meet at 9 o'clock at the secret place.";

$encrypted_data = mcrypt_ecb (MCRYPT_3DES, $key, $input, MCRYPT_ENCRYPT);

Or:

$key = "this is a secret key";
$input = "Let us meet at 9 o'clock at the secret place.";

$td = mcrypt_module_open('tripledes', '', 'ecb', '');
$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, $key, $iv);
$encrypted_data = mcrypt_generic($td, $input);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
like image 167
awgy Avatar answered Sep 25 '22 12:09

awgy