Keep in mind that the mcrypt functions do not implement padding like e.g. pkcs#5. This causes the problem with zero bytes at the end and the sting cannot be correctly decoded in other environments.
For an example how to add pkcs 5 padding, see ref.mcrypt.php
mcrypt_module_open
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_module_open — Abre el módulo del algoritmo y el modo a ser utilizados
Descripción
Esta función abre el módulo del algoritmo y el modo a ser utilizados. El nombre del algoritmo es especificado en algorithm, por ejemplo "twofish" o una de las constantes MCRYPT_ciphername. El módulo es cerrado al invocar a mcrypt_module_close().
Parámetros
- algorithm
-
El algoritmo a ser utilizado.
- algorithm_directory
-
El parámetro algorithm_directory se utiliza para ubicar el módulo de encriptación. Cuando se pasa un nombre de directorio, es utilizado. Cuando se pasa una cadena vacía (""), se utiliza el valor configurado en la directiva mcrypt.algorithms_dir del fichero php.ini. Cuando no se pasa nada, el directorio por defecto que se utiliza es en el que libmcrypt fue compilado (generalmente /usr/local/lib/libmcrypt).
- mode
-
El modo a ser utilizado.
- mode_directory
-
El parámetro mode_directory se utiliza para ubicar el módulo de encriptación. Cuando se pasa un nombre de directorio, es utilizado. Cuando se pasa una cadena vacía (""), se utiliza el valor configurado en la directiva mcrypt.modes_dir del fichero php.ini. Cuando no se pasa nada, el directorio por defecto que se utiliza es en el que libmcrypt fue compilado (generalmente /usr/local/lib/libmcrypt).
Valores devueltos
Normalmente devuelve un descriptor de cifrado, o FALSE en caso de error.
Ejemplos
Example #1 Ejemplo de mcrypt_module_open()
<?php
$td = mcrypt_module_open(MCRYPT_DES, '',
MCRYPT_MODE_ECB, '/usr/lib/mcrypt-modes');
$td = mcrypt_module_open('rijndael-256', '', 'ofb', '');
?>
La primer línea del ejemplo anterior intentará abrir el cifrador DES desde el directorio por defecto y el modo EBC desde el directorio /usr/lib/mcrypt-modes. El segundo ejemplo utiliza cadenas como nombres para el cifrador y el modo, esto solo funciona cuando la extensión está enlazado con libmcrypt 2.4.x o 2.5.x.
Example #2 Utilizando mcrypt_module_open() en el proceso de cifrado
<?php
/* Open the cipher */
$td = mcrypt_module_open('rijndael-256', '', 'ofb', '');
/* Create the IV and determine the keysize length, use MCRYPT_RAND
* on Windows instead */
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_DEV_RANDOM);
$ks = mcrypt_enc_get_key_size($td);
/* Create key */
$key = substr(md5('very secret key'), 0, $ks);
/* Intialize encryption */
mcrypt_generic_init($td, $key, $iv);
/* Encrypt data */
$encrypted = mcrypt_generic($td, 'This is very important data');
/* Terminate encryption handler */
mcrypt_generic_deinit($td);
/* Initialize encryption module for decryption */
mcrypt_generic_init($td, $key, $iv);
/* Decrypt encrypted string */
$decrypted = mdecrypt_generic($td, $encrypted);
/* Terminate decryption handle and close module */
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
/* Show string */
echo trim($decrypted) . "\n";
?>
Ver también
- mcrypt_module_close() - Cierra el módulo mcrypt
- mcrypt_generic() - Esta función encripta datos
- mdecrypt_generic() - Desencripta datos
- mcrypt_generic_init() - Esta función inicializa todos los buffers requeridos para el cifrado
- mcrypt_generic_deinit() - Esta función deinicializa un módulo de cifrado
about the previous comments on hex formatting and capitalization as a way to improve the key:
this would seem pretty obvious, but it is a choice to be limited to only hex characters ([0-9a-z]); you can get the original RAW output from md5() or sha1() and not the default readable hex formatting.
the result of a raw output will be 16 o 20 (depending on the hash function being used) series of chars in the range 0-255. way better than [0-9a-z] and even [0-9a-zA-Z].
16 or 20 is generally lower than the maximum key lenght ($ks in the example), but you can append two or more keys together:
<?php
$human_key1 = 'something very secret';
$human_key2 = 'something else very secret';
// 40 bytes binary key using two "human readable" keys and sha1.
$bigger_binary_key = sha1($human_key1, true) . sha1($human_key2, true);
// then just use it as you would (extract taken from the example)
$key = substr($bigger_binary_key, 0, $ks);
?>
... or you can automatically split one large "human key" into two or more parts, hash those parts with sha1 (raw output!) and merge them together again (in original order or rearrange, salt, transform them as you like) to get a binary key of 40, 60, 80 or more chars depending on the number of parts the secret key has been splitted =)
A slight improvement of dinamic's function to create a key:
I think the weak point is that capitals are always used in the same part of the string. The following code capitalizes random characters of the string, making the key less predictable:
<?php
$key = substr($key1, 0, $ks/2) . substr($key2, (round(strlen($key2) / 2)), $ks/2);
$key = substr($key.$key1.$key2.$key1,0,$ks);
$buffer = str_split($key);
$limit = count($buffer)-1;
srand((float)microtime() * 1000000);
$end = rand(0, $limit);
$a = 0;
// replace random chars with capitals
while ($a < $end) {
list($usec, $sec) = explode(' ', microtime());
$seed = ((float)$sec) + ((float) $usec * 100000);
mt_srand($seed);
$index = mt_rand(0,$limit);
$buffer[$index] = strtoupper($buffer[$index]);
$a++;
}
$key = join('', $buffer);
?>
Also it should be pointed that md5() and/or sha1() should not be used while forming your key for the mcrypt. This is so because hex encoding uses a set of only 16 characters [0-9a-f], which is equivalent to 4 bits, and thus halve the strength of your encryption: 4 x 32 = 128-bit.
I have re-wrote the example shown, so here is my suggestion to get real 256-bit encryption:
<?php
$key1 = "this is a secret key";
$key2 = "this is the second secret key";
$input = "Let us meet at 9 o'clock at the secret place.";
$length = strlen($input);
/* Open the cipher */
$td = mcrypt_module_open('rijndael-256', '', 'cbc', '');
/* Create the IV and determine the keysize length, use MCRYPT_RAND
* on Windows instead */
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
$ks = mcrypt_enc_get_key_size($td);
/* Create key */
$key1 = md5($key1);
$key2 = md5($key2);
$key = substr($key1, 0, $ks/2) . substr(strtoupper($key2), (round(strlen($key2) / 2)), $ks/2);
$key = substr($key.$key1.$key2.strtoupper($key1),0,$ks);
/* Intialize encryption */
mcrypt_generic_init($td, $key, $iv);
/* Encrypt data */
$encrypted = mcrypt_generic($td, $input);
/* Terminate encryption handler */
mcrypt_generic_deinit($td);
/* Initialize encryption module for decryption */
mcrypt_generic_init($td, $key, $iv);
/* Decrypt encrypted string */
$decrypted = mdecrypt_generic($td, $encrypted);
/* Terminate decryption handle and close module */
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
/* Show string */
echo "Text: ".substr($decrypted,0,$length) . "<br>";
echo "Encoded: ".$encrypted ."<br>";
echo "<br>key1: $key1 <br>key2: $key2<br>created key: $key";
?>
In the text example:
$key = substr(md5('very secret key'), 0, $ks);
Builds a key of $ks/2 effective bytes.
Doing a trim($decrypted) will remove the null padding that may occur as a result of decryption.
The problem is if you're encrypting something like a MSWord document which can commonly end with nulls. The result $decrypted will be smaller than the original cleartext - which will then fail to open in MSOffice.
To get around this, make sure you store the length of the original cleartext, and when you decrypt it, do:
$decrypted = substr(mdecrypt_generic($td, $encrypted), 0, $originalLength);
