Funciones de Cifrado Mcrypt
Introducción
Esta es una interfaz con la biblioteca mcrypt, la cual soporta una gran variedad de algoritmos de bloque como DES, TripleDES, Blowfish (por defecto), 3-WAY, SAFER-SK64, SAFER-SK128, TWOFISH, TEA, RC2 y GOST en los modos de cifrado CBC, OFB, CFB y ECB. Adicionalmente, soporta RC6 e IDEA, los cuales se consideran "no-libres".
Requisitos
Estas funciones trabajan usando » mcrypt. Para usar la biblioteca, descargue libmcrypt-x.x.tar.gz desde » https://mcrypt.sourceforge.net/ y siga las instrucciones de instalación incluidas. Los usuarios de windows encontrarán todos los binarios compilados de mcrypt que se necesitan en » https://files.edin.dk/php/win32/mcrypt/.
A partir de PHP 5.0.0, es necesario usar la versión 2.5.6 o superior de libmcrypt.
Si ha enlazado el software contra libmcrypt 2.4.x o versiones superiores, los siguientes algoritmos de bloque adicionales son soportados: CAST, LOKI97, RIJNDAEL, SAFERPLUS, SERPENT y los siguientes cifrados de secuencia: ENIGMA (cifrado), PANAMA, RC4 y WAKE. Con libmcrypt 2.4.x o superior, también se encuentra disponible otro modo de cifrado; nOFB.
Instalación
You need to compile PHP with the --with-mcrypt[=DIR] parameter to enable this extension. DIR is the mcrypt install directory. Make sure you compile libmcrypt with the option --disable-posix-threads.
Configuración en tiempo de ejecución
El comportamiento de estas funciones está afectado por los valores definidos en php.ini.
Name | Default | Changeable | Changelog |
---|---|---|---|
mcrypt.algorithms_dir | NULL | PHP_INI_ALL | Available since PHP 4.0.2. |
mcrypt.modes_dir | NULL | PHP_INI_ALL | Available since PHP 4.0.2. |
Tipos de recursos
mcrypt_module_open() devuelve un descriptor de encripción.
Constantes predefinidas
Estas constantes están definidas por esta extensión y estarán disponibles solamente cuando la extensión ha sido o bien compilada dentro de PHP o grabada dinámicamente en tiempo de ejecución.
Mcrypt can operate in four block cipher modes (CBC, OFB, CFB, and ECB). If linked against libmcrypt-2.4.x or higher the functions can also operate in the block cipher mode nOFB and in STREAM mode. Below you find a list with all supported encryption modes together with the constants that are defines for the encryption mode. For a more complete reference and discussion see Applied Cryptography by Schneier (ISBN 0-471-11709-9).
- MCRYPT_MODE_ECB (electronic codebook) is suitable for random data, such as encrypting other keys. Since data there is short and random, the disadvantages of ECB have a favorable negative effect.
- MCRYPT_MODE_CBC (cipher block chaining) is especially suitable for encrypting files where the security is increased over ECB significantly.
- MCRYPT_MODE_CFB (cipher feedback) is the best mode for encrypting byte streams where single bytes must be encrypted.
- MCRYPT_MODE_OFB (output feedback, in 8bit) is comparable to CFB, but can be used in applications where error propagation cannot be tolerated. It's insecure (because it operates in 8bit mode) so it is not recommended to use it.
- MCRYPT_MODE_NOFB (output feedback, in nbit) is comparable to OFB, but more secure because it operates on the block size of the algorithm.
- MCRYPT_MODE_STREAM is an extra mode to include some stream algorithms like WAKE or RC4.
Some other mode and random device constants:
Cifrados mcrypt
Aquà se encuentra una lista de cifrados que son soportados actualmente por la extensión mcrypt. Para una lista completa de los cifrados soportados, consulte las definiciones al final de mcrypt.h. La regla general con la API de mcrypt-2.2.x API es que puede acceder al cifrado desde PHP mediante MCRYPT_nombre_cifrado. Con la API de libmcrypt-2.4.x y libmcrypt-2.5.x API estas constantes funcionan también, pero es posible especificar el nombre del cifrado como una cadena con una llamada a mcrypt_module_open().
- MCRYPT_3DES
- MCRYPT_ARCFOUR_IV (libmcrypt > 2.4.x únicamente)
- MCRYPT_ARCFOUR (libmcrypt > 2.4.x únicamente)
- MCRYPT_BLOWFISH
- MCRYPT_CAST_128
- MCRYPT_CAST_256
- MCRYPT_CRYPT
- MCRYPT_DES
- MCRYPT_DES_COMPAT (libmcrypt 2.2.x únicamente)
- MCRYPT_ENIGMA (libmcrypt > 2.4.x únicamente, alias para MCRYPT_CRYPT)
- MCRYPT_GOST
- MCRYPT_IDEA (non-free)
- MCRYPT_LOKI97 (libmcrypt > 2.4.x únicamente)
- MCRYPT_MARS (libmcrypt > 2.4.x únicamente, no-libre)
- MCRYPT_PANAMA (libmcrypt > 2.4.x únicamente)
- MCRYPT_RIJNDAEL_128 (libmcrypt > 2.4.x únicamente)
- MCRYPT_RIJNDAEL_192 (libmcrypt > 2.4.x únicamente)
- MCRYPT_RIJNDAEL_256 (libmcrypt > 2.4.x únicamente)
- MCRYPT_RC2
- MCRYPT_RC4 (libmcrypt 2.2.x únicamente)
- MCRYPT_RC6 (libmcrypt > 2.4.x únicamente)
- MCRYPT_RC6_128 (libmcrypt 2.2.x únicamente)
- MCRYPT_RC6_192 (libmcrypt 2.2.x únicamente)
- MCRYPT_RC6_256 (libmcrypt 2.2.x únicamente)
- MCRYPT_SAFER64
- MCRYPT_SAFER128
- MCRYPT_SAFERPLUS (libmcrypt > 2.4.x únicamente)
- MCRYPT_SERPENT(libmcrypt > 2.4.x únicamente)
- MCRYPT_SERPENT_128 (libmcrypt 2.2.x únicamente)
- MCRYPT_SERPENT_192 (libmcrypt 2.2.x únicamente)
- MCRYPT_SERPENT_256 (libmcrypt 2.2.x únicamente)
- MCRYPT_SKIPJACK (libmcrypt > 2.4.x únicamente)
- MCRYPT_TEAN (libmcrypt 2.2.x únicamente)
- MCRYPT_THREEWAY
- MCRYPT_TRIPLEDES (libmcrypt > 2.4.x únicamente)
- MCRYPT_TWOFISH (para versinos mcrypt 2.x más antiguas, o mcrypt > 2.4.x )
- MCRYPT_TWOFISH128 (TWOFISHxxx se encuentran disponibles en versiones 2.x más recientes, pero no en las versiones 2.4.x)
- MCRYPT_TWOFISH192
- MCRYPT_TWOFISH256
- MCRYPT_WAKE (libmcrypt > 2.4.x únicamente)
- MCRYPT_XTEA (libmcrypt > 2.4.x únicamente)
Usted debe (en modos CFB y OFB) o puede (en modo CBC) entregar un vector de inicialización (IV, por sus siglas en inglés) a la respectiva función de cifrado. El IV debe ser único y debe ser el mismo cuando se realice descifrado/cifrado. Con datos que sean almacenados en forma cifrada, usted puede tomar la salida de una función del Ãndice bajo el cual se encuentren almacenados los datos (p.ej. la llave MD5 del nombre de archivo). Alternativamente, puede transmitir el IV junto con los datos cifrados (vea el capÃtulo 9.3 de Applied Cryptography by Schneier (ISBN 0-471-11709-9) para una discusión de este tópico).
Ejemplos
Mcrypt puede usarse para cifrar y descifrar usando los cifrados mencionados anteriormente. Si ha enlazado el software contra libmcrypt-2.2.x, los cuatro comandos importantes de mcrypt (mcrypt_cfb(), mcrypt_cbc(), mcrypt_ecb(), y mcrypt_ofb()) pueden operar en ambos modos, los cuales son llamados MCRYPT_ENCRYPT y MCRYPT_DECRYPT, respectivamente.
Example#1 Cifrar un valor de entrada con TripleDES bajo 2.2.x en modo ECB
<?php
$llave = "esta es una llave secreta";
$entrada = "Encontrémonos a las 9 en punto en el lugar secreto.";
$datos_cifrados = mcrypt_ecb (MCRYPT_3DES, $llave, $entrada, MCRYPT_ENCRYPT);
?>
Si ha enlazado el software contra libmcrypt 2.4.x o 2.5.x, éstas funciones aun están disponibles, pero es recomendable que use las funciones avanzadas.
Example#2 Encriptar un valor de entrada con TripleDES bajo 2.4.x y versiones superiores, en modo ECB
<?php
$llave = "esta es una llave secreta";
$entrada = "Encontrémonos a las 9 en punto en el lugar secreto.";
$td = mcrypt_module_open('tripledes', '', 'ecb', '');
$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, $llave, $iv);
$datos_cifrados = mcrypt_generic($td, $entrada);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
?>
Table of Contents
- mcrypt_cbc — Encripta/desencripta datos en modo CBC
- mcrypt_cfb — Encripta/desencripta datos en modo CFB
- mcrypt_create_iv — Crea un vector de inicialización (IV) a partir de una fuente aleatoria
- mcrypt_decrypt — Decrypts crypttext with given parameters
- mcrypt_ecb — Encripta/desencripta datos en modo ECB
- mcrypt_enc_get_algorithms_name — Returns the name of the opened algorithm
- mcrypt_enc_get_block_size — Returns the blocksize of the opened algorithm
- mcrypt_enc_get_iv_size — Returns the size of the IV of the opened algorithm
- mcrypt_enc_get_key_size — Returns the maximum supported keysize of the opened mode
- mcrypt_enc_get_modes_name — Returns the name of the opened mode
- mcrypt_enc_get_supported_key_sizes — Returns an array with the supported keysizes of the opened algorithm
- mcrypt_enc_is_block_algorithm_mode — Checks whether the encryption of the opened mode works on blocks
- mcrypt_enc_is_block_algorithm — Checks whether the algorithm of the opened mode is a block algorithm
- mcrypt_enc_is_block_mode — Checks whether the opened mode outputs blocks
- mcrypt_enc_self_test — This function runs a self test on the opened module
- mcrypt_encrypt — Encrypts plaintext with given parameters
- mcrypt_generic_deinit — This function deinitializes an encryption module
- mcrypt_generic_end — This function terminates encryption
- mcrypt_generic_init — This function initializes all buffers needed for encryption
- mcrypt_generic — This function encrypts data
- mcrypt_get_block_size — Obtiene el tamaño de bloque del cifrado indicado
- mcrypt_get_cipher_name — Obtiene el nombre del cifrado especificado
- mcrypt_get_iv_size — Returns the size of the IV belonging to a specific cipher/mode combination
- mcrypt_get_key_size — Obtiene el tamaño de la clave de un cifrado
- mcrypt_list_algorithms — Get an array of all supported ciphers
- mcrypt_list_modes — Get an array of all supported modes
- mcrypt_module_close — Close the mcrypt module
- mcrypt_module_get_algo_block_size — Returns the blocksize of the specified algorithm
- mcrypt_module_get_algo_key_size — Returns the maximum supported keysize of the opened mode
- mcrypt_module_get_supported_key_sizes — Returns an array with the supported keysizes of the opened algorithm
- mcrypt_module_is_block_algorithm_mode — Returns if the specified module is a block algorithm or not
- mcrypt_module_is_block_algorithm — This function checks whether the specified algorithm is a block algorithm
- mcrypt_module_is_block_mode — Returns if the specified mode outputs blocks or not
- mcrypt_module_open — Opens the module of the algorithm and the mode to be used
- mcrypt_module_self_test — This function runs a self test on the specified module
- mcrypt_ofb — Encripta/desencripta datos en modo OFB
- mdecrypt_generic — Decrypt data