downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

mcrypt_cbc> <mcal_week_of_year
[edit] Last updated: Mon, 01 Nov 2010

view this page in

LXXV. 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 http://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 http://ftp.emini.dk/pub/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.

Tabla 1. Mcrypt configuration options

NameDefaultChangeableChangelog
mcrypt.algorithms_dirNULLPHP_INI_ALLAvailable since PHP 4.0.2.
mcrypt.modes_dirNULLPHP_INI_ALLAvailable since PHP 4.0.2.
For further details and definitions of the PHP_INI_* constants, see the Apéndice G.

Tipos de recursos

Esta extensión no tiene ningún tipo de recurso definido.

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:

MCRYPT_ENCRYPT (integer)

MCRYPT_DECRYPT (integer)

MCRYPT_DEV_RANDOM (integer)

MCRYPT_DEV_URANDOM (integer)

MCRYPT_RAND (integer)

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.

Ejemplo 1. Cifrar un valor de entrada con TripleDES bajo 2.2.x en modo ECB

<?php
$llave
= "esta es una llave secreta";
$entrada = "Encontr&eacute;monos a las 9 en punto en el lugar secreto.";

$datos_cifrados = mcrypt_ecb (MCRYPT_3DES, $llave, $entrada, MCRYPT_ENCRYPT);
?>
Este ejemplo le entregará los datos cifrados como una cadena en $datos_cifrados.

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.

Ejemplo 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&eacute;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);
?>
Este ejemplo le entregará los datos cifrados como una cadena en $datos_cifrados. Para un ejemplo completo, consulte mcrypt_module_open().

Tabla de contenidos
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


mcrypt_cbc> <mcal_week_of_year
[edit] Last updated: Mon, 01 Nov 2010
 
add a note add a note User Contributed Notes Funciones de Cifrado Mcrypt
patrickdk at patrickdk dot com 06-Aug-2010 10:30
This works completely with mysql aes, even long keys.

<?php
function mysql_aes_decrypt($val,$ky)
{
   
$key="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
    for(
$a=0;$a<strlen($ky);$a++)
     
$key[$a%16]=chr(ord($key[$a%16]) ^ ord($ky[$a]));
   
$mode = MCRYPT_MODE_ECB;
   
$enc = MCRYPT_RIJNDAEL_128;
   
$dec = @mcrypt_decrypt($enc, $key, $val, $mode, @mcrypt_create_iv( @mcrypt_get_iv_size($enc, $mode), MCRYPT_DEV_URANDOM ) );
    return
rtrim($dec,(( ord(substr($dec,strlen($dec)-1,1))>=0 and ord(substr($dec, strlen($dec)-1,1))<=16)? chr(ord( substr($dec,strlen($dec)-1,1))):null));
}

function
mysql_aes_encrypt($val,$ky)
{
   
$key="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
    for(
$a=0;$a<strlen($ky);$a++)
     
$key[$a%16]=chr(ord($key[$a%16]) ^ ord($ky[$a]));
   
$mode=MCRYPT_MODE_ECB;
   
$enc=MCRYPT_RIJNDAEL_128;
   
$val=str_pad($val, (16*(floor(strlen($val) / 16)+(strlen($val) % 16==0?2:1))), chr(16-(strlen($val) % 16)));
    return
mcrypt_encrypt($enc, $key, $val, $mode, mcrypt_create_iv( mcrypt_get_iv_size($enc, $mode), MCRYPT_DEV_URANDOM));
}
?>
p ete postma - googlemail.com 30-Oct-2009 09:42
mcrypt module initialization failed

I found this circumstance:

usemcrypt.php:
<?php
 
function protect() {
 
//some mcrypt/decrypt command
 
}
?>

filea.php:
<?php
include_once('usemcrypt.php');

function
a() {
 
protect();
}
?>

fileb.php
<?php
function b() {
  include_once(
'usemcrypt.php');
 
protect();
}
?>

filea.php and a() work fine
fileb.php and b() will report a mcrypt module initialization failed

I am assuming you can't pull that module in on the fly. If you use a file that calls mcrypt, it has to be included at the head, not in a function.
manyagain 04-Jul-2009 08:44
if you don't have mcrypt installed, try phpseclib - http://phpseclib.sourceforge.net

includes pure-php implementations of des, 3des, rc4, aes, and rijndael.  uses mcrypt if it's available and a pure-php implementation otherwise.  it also has the distinction of having the fastest existent pure-php aes implementation as per section 3.5.5. "Speed Comparisons" of the documentation.
Rafael M. Salvioni 27-Nov-2008 04:26
The follow function is a implementation of the RC4 cypher algorithm in pure PHP code.

The function is used to encrypt and decrypt data.

<?php
/**
 * Crypt/decrypt strings with RC4 stream cypher algorithm.
 *
 * @param string $key Key
 * @param string $data Encripted/pure data
 * @see   http://pt.wikipedia.org/wiki/RC4
 * @return string
 */
function rc4($key, $data)
{
   
// Store the vectors "S" has calculated
   
static $SC;
   
// Function to swaps values of the vector "S"
   
$swap = create_function('&$v1, &$v2', '
        $v1 = $v1 ^ $v2;
        $v2 = $v1 ^ $v2;
        $v1 = $v1 ^ $v2;
    '
);
   
$ikey = crc32($key);
    if (!isset(
$SC[$ikey])) {
       
// Make the vector "S", basead in the key
       
$S    = range(0, 255);
       
$j    = 0;
       
$n    = strlen($key);
        for (
$i = 0; $i < 255; $i++) {
           
$char  = ord($key{$i % $n});
           
$j     = ($j + $S[$i] + $char) % 256;
           
$swap($S[$i], $S[$j]);
        }
       
$SC[$ikey] = $S;
    } else {
       
$S = $SC[$ikey];
    }
   
// Crypt/decrypt the data
   
$n    = strlen($data);
   
$data = str_split($data, 1);
   
$i    = $j = 0;
    for (
$m = 0; $m < $n; $m++) {
       
$i        = ($i + 1) % 256;
       
$j        = ($j + $S[$i]) % 256;
       
$swap($S[$i], $S[$j]);
       
$char     = ord($data[$m]);
       
$char     = $S[($S[$i] + $S[$j]) % 256] ^ $char;
       
$data[$m] = chr($char);
    }
    return
implode('', $data);
}
?>
artem at it-nt dot ru 29-May-2008 12:25
And some code for LM hash:

<?php
function LMhash($string)
{
   
$string = strtoupper(substr($string,0,14));

   
$p1 = LMhash_DESencrypt(substr($string, 0, 7));
   
$p2 = LMhash_DESencrypt(substr($string, 7, 7));

    return
strtoupper($p1.$p2);
}

function
LMhash_DESencrypt($string)
{
   
$key = array();
   
$tmp = array();
   
$len = strlen($string);

    for (
$i=0; $i<7; ++$i)
       
$tmp[] = $i < $len ? ord($string[$i]) : 0;

   
$key[] = $tmp[0] & 254;
   
$key[] = ($tmp[0] << 7) | ($tmp[1] >> 1);
   
$key[] = ($tmp[1] << 6) | ($tmp[2] >> 2);
   
$key[] = ($tmp[2] << 5) | ($tmp[3] >> 3);
   
$key[] = ($tmp[3] << 4) | ($tmp[4] >> 4);
   
$key[] = ($tmp[4] << 3) | ($tmp[5] >> 5);
   
$key[] = ($tmp[5] << 2) | ($tmp[6] >> 6);
   
$key[] = $tmp[6] << 1;
   
   
$is = mcrypt_get_iv_size(MCRYPT_DES, MCRYPT_MODE_ECB);
   
$iv = mcrypt_create_iv($is, MCRYPT_RAND);
   
$key0 = "";
   
    foreach (
$key as $k)
       
$key0 .= chr($k);
   
$crypt = mcrypt_encrypt(MCRYPT_DES, $key0, "KGS!@#$%", MCRYPT_MODE_ECB, $iv);

    return
bin2hex($crypt);
}
?>

Some optimization?
phpknights at pookmail dot com 01-Feb-2008 01:18
The Pear class Crypt/Blowfish.php will use the mcrypt module if available but the mcrypt module is not required.

Some very easy Pear and example pseudocode to protect your data by encrypting your databases with a one-way hash and blowfish symmetric encryption.
http://en.wikibooks.org/wiki/Cryptography/Database_protection

Using a one-way hash and blowfish symmetric encryption.
1. Insert a record of John Doe in an encrypted database.
2. Get the encrypted record of user John Doe and decrypt the data.

1. Insert a record of John Doe in an encrypted database.
<?php

       
require_once("Crypt/Blowfish.php"); // a Pear class

       
$aRecord['email']       =       "johndoe@anisp.localhost"; // The Primary key
       
$aRecord['name']        =       "John Doe";
       
$aRecord['creditnr']    =       "0192733652342" ;

       
// crypt - one-way encryption
       
$cipher_key = crypt( $aRecord['email'] , "AN_SECRET_COMPANY_SALT");

       
$bf = new Crypt_Blowfish('ecb');
       
$bf->setKey( $cipher_key );

       
// crypt_blowfish symmetric encryption to encrypt the data
       
$aRecord['email']       = $bf->encrypt( $aRecord['email'] );
       
$aRecord['name']        = $bf->encrypt( $aRecord['name'] );
       
$aRecord['creditnr']    = $bf->encrypt( $aRecord['creditnr'] );

       
$result = sqlInsert( $aRecord ) ;
?>

2. Get the encrypted record of user John Doe and decrypt the data.
<?php

       
require_once("Crypt/Blowfish.php");  // a Pear class

       
$primary_key = "johndoe@anisp.localhost";

       
// crypt - one-way encryption
       
$cipher_key = crypt$primary_key , "AN_SECRET_COMPANY_SALT");

       
$bf = new Crypt_Blowfish('ecb');
       
$bf->setKey( $cipher_key );

       
// crypt_blowfish symmetric encryption to ecrypt the primary key for a sql select
       
$select_key = $bf->encrypt$primary_key ) ;

       
$aRecord = sqlSelectWithPKEY( $select_key );

       
// crypt_blowfish symmetric encryption to decrypt the data
       
$aRecord['email']       = $bf->decrypt( $aRecord['email'] );
       
$aRecord['name']        = $bf->decrypt( $aRecord['name'] );
       
$aRecord['creditnr']    = $bf->decrypt( $aRecord['creditnr'] );
?>

Thanks for reading this.
Kevin 23-Jan-2008 09:37
Solved Problem:

when compiling php --with-mcrypt, phpinfo() says, that mcrypt ist enabled, but
"Supported ciphers none" and
"Supported modes none"

In order to get mcrypt to work in php, you have to configure and compile the libmcrypt source package with the following options:
./configure --disable-posix-threads --enable-dynamic-loading
Ivan Frederiks 28-Apr-2007 07:03
To enable mcrypt extension under Windows you need to:
1) uncomment line "extension=php_mcrypt.dll" in php.ini
2) download libmcrypt.dll from http://files.edin.dk/php/win32/mcrypt/ and put it to System32 directory (for example C:\Windows\System32).
Tested on Windows XP+Apache 1.3.37+PHP 4.4.6 (as SAPI module!!!)

P.S.
I wrote this because I got "Cannot load mcrypt extension. Please check your PHP configuration." from phpMyAdmin when I simply uncommented "extension=php_mcrypt.dll" line.
duerra_NOT_THIS_ at pushitlive dot net 20-Sep-2006 12:56
For those of you that need to use PKCS#5 padding, the mcrypt API's for PHP do not support it.  However, you can DIY using the following:

<?php

function encrypt_something($input)
{
   
$size = mcrypt_get_block_size('des', 'ecb');
   
$input = pkcs5_pad($input, $size);
   
   
$key = 'YOUR SECRET KEY HERE';
   
$td = mcrypt_module_open('des', '', 'ecb', '');
   
$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
   
mcrypt_generic_init($td, $key, $iv);
   
$data = mcrypt_generic($td, $input);
   
mcrypt_generic_deinit($td);
   
mcrypt_module_close($td);
   
$data = base64_encode($data);
    return
$data;
}

function
pkcs5_pad ($text, $blocksize)
{
   
$pad = $blocksize - (strlen($text) % $blocksize);
    return
$text . str_repeat(chr($pad), $pad);
}

function
pkcs5_unpad($text)
{
   
$pad = ord($text{strlen($text)-1});
    if (
$pad > strlen($text)) return false;
    if (
strspn($text, chr($pad), strlen($text) - $pad) != $pad) return false;
    return
substr($text, 0, -1 * $pad);
}
?>
rolf at winmutt dot com 10-Mar-2006 12:19
mysql AES_ENCRYPT() compatibly function for PHP :

<?php
function mysql_aes_encrypt($val,$ky) {
   
$mode=MCRYPT_MODE_ECB;   
   
$enc=MCRYPT_RIJNDAEL_128;
   
$val=str_pad($val, (16*(floor(strlen($val) / 16)+(strlen($val) % 16==0?2:1))), chr(16-(strlen($val) % 16)));
    return
mcrypt_encrypt($enc, $ky, $val, $mode, mcrypt_create_iv( mcrypt_get_iv_size($enc, $mode), MCRYPT_DEV_URANDOM));
}
?>

Please note that if the strlen($ky)>16 then this function will not be compatible.
vincent at verbrugh dot nl 01-Mar-2006 01:55
If you plan to use Mcrypt Encryption to store encrypted data (e.g. passwords) in a (MySQL) database make sure to set the column to BLOB rather than VARCHAR. Otherwise the data may change which can give unexpected results if you decrypt the value.
Jerry Hathaway 16-Feb-2006 10:23
After benchmarking AES in 256-bit operation, I've concluded that CBC is far faster than OFB.  Using a 14.9 MiB file, on average...

Encrypt in CBC:   1.9 seconds
Encrypt in OFB:   45.7 seconds (same as CFB)
Just reading the file:  ~.53 seconds

After some research, I've concluded that OFB and CFB are slightly more secure than CBC, however I believe the performance difference to be due to an implementation issue.

As a side note on ECB:  As stated in the wiki linked to below, ECB is wholly inadequate.  It not use an IV (whether it was supplied ot MCrypt or not), meaning the same key and plaintext always produce the same ciphertext and it doesn't hide patterns.  The site shows an excellent example of this.

Very useful info:
http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation
triptripon at gmail dot com 05-Feb-2006 03:28
Regarding storing the result on a postgres DB that uses Unicode (follow up to a post below).
You don't need to change the DB's encoding to ASCII.
Simply use BASE64 to encode the result, it's perfectly safe.
use base64_decode before you decrypt.
-- Tomer Levinboim
coz AT metamule D0T com 04-Nov-2005 05:15
If you're going to encrypt data with something like this and store it in postgres.

<?php
function encrypt($string, $key){
       
$result = '';
        for(
$i=1; $i<=strlen($string); $i++){
           
$char = substr($string, $i-1, 1);
           
$keychar = substr($key, ($i % strlen($key))-1, 1);
           
$char = chr(ord($char)+ord($keychar));
           
$result.=$char;
        }
        return
$result;
    }
?>

Make sure when you create your database to set the encoding to SQL_ASCII because you won't be able to store this data in a database that uses UNICODE
joseph-at-digiweb-dot-net-dot-nz 30-Oct-2005 05:22
A further note for those doing interop between PHP and Java:

If you're using the BouncyCastle library on the Java side, then you can use the ZeroBytePadding mode now available in it. Mcrypt pads the data with Nulls rather than spaces....

I've sucessfully done interop using Blowfish/CBC/ZeroBytePadding between PHP and Java this way.
paul dot lewis at absolutegenius dot co dot uk 13-Jul-2005 08:33
I've spent the majority of the day attempting to get mcrypt to work under IIS6 with Windows Server 2003 (Web Edition) and PHP 5.0.4

There seems to be some incompatability with enabling certain extensions (mcrypt being one) when you are running PHP as ISAPI in this environment.

The way to solve the problem (the error will be that it cannot load php_mcrypt.dll - access is denied) is to run in CGI. While this isn't supposed to be as good performance wise, if you need the mcrypt support (or Oracle support, too, I believe) then this is the only way I've found to do it.
MGTech 20-May-2005 12:02
Please, mind that a XOR Encryption can't compete with a block cipher like AES or IDEA, but if you really want to use a stream cipher the more secure RC4 is the right alternative.
A XOR Encryption is only a bit useful if you encrypt data for private use, otherwise it is a frankly a security risk.
Jurgen Schwietering 23-Nov-2004 01:20
Attention when using keys longer than the actual key size (i.e. 160 bit instead of 128 bit).

It will work inbetween PHP scripts, but might cause problems when using openssl or other packages with this integration of mcrypt. Cut them always to the supported size (mcrypt_enc_get_key_size) to avoid sleepless hours.
Anonymous 19-Nov-2004 08:18
Or, if you don't have the mcrypt library, you can just use these functions:

<?php
function Encrypt($string, $key)
{
$result = '';
for(
$i=1; $i<=strlen($string); $i++)
{
$char = substr($string, $i-1, 1);
$keychar = substr($key, ($i % strlen($key))-1, 1);
$char = chr(ord($char)+ord($keychar));
$result.=$char;
}
return
$result;
}

function
Decrypt($string, $key)
{
$result = '';
for(
$i=1; $i<=strlen($string); $i++)
{
$char = substr($string, $i-1, 1);
$keychar = substr($key, ($i % strlen($key))-1, 1);
$char = chr(ord($char)-ord($keychar));
$result.=$char;
}
return
$result;
}
?>

It's very simple encryption, but as long as the key stays secret, very powerful.
dzelko at hotmail dot com 14-May-2004 12:11
Windows IIS Users - Problems installing/using mcrypt and other extensions
::
I've noticed a lot of users complaining in forums that they have difficult time getting mcrypt extension to function/ finding or installing working .dlls when using IIS:
::
Easy solution that works well for me: (IIS 6 on Win 2003 Svr and IIS on XP Pro) #customized install later for increased security#
1. Install current stable php version using windows installer #gets php up and running quickly#
2. Download Windows Binary Package
3. Extract Package Library to PHP folder installer generates - overwrite all
4. Edit php.ini as appropriate.  (specifically for mcrypt uncomment mcrypt=php_mcrypt.dll)
::
No mo' problems.
groundzero at zuavra dot net 09-Jan-2004 05:08
If you've ever compiled PHP from source (any version) you may be familiar with the [in]famous MCRYPT_BLOWFISH_128 compilation error that appears when you attempt to compile --with-mcrypt. It occurs often on Debian but not only there. The problem: during compilation, the PHP configure script always assumes that libmcrypt has been built in conjunction with libltdl. Whenever that is not the case, PHP compilation will fail later saying certain headers (such as the above blowfish example) are missing from mcrypt.h (which is misleading, they're not supposed to be there nor looked after if libltdl was properly involved). Solution: make sure your libmcrypt was linked against libltdl before you even start configuring PHP. You can check by running 'ldd lybmcrypt.so' and verifying that libltdl appears in the output. libltdl can be found in libltld[3][-dev] on Debian or in libtool-libs on Red Hat.
simms 03-Oct-2003 02:03
DEBIAN users: avoid mcrypt installation headaches.
to add mcrypt support to an existing php installation, get root and run

apt-get install php4-mcrypt

restart your webserver, and voila.
steve@itemfront dot ltd dot uk 29-Sep-2003 05:17
Just spent a while getting mcrypt support working with php. Used libmcrypt version 2.5.7 with php 4.3.3. Out of the box it just won't work. Configure as follows:

libmcrypt:

  ./configure --disable-posix-threads --enable-dynamic-loading

php: ( as you can see, it's built for a SunONE server, but that's the easy bit to configure! )

./configure  --with-nsapi=/usr/iplanet/servers --enable-sigchld --with-ldap --with-zlib-dir=/usr/lib --with-mcrypt=<srcdir>/libmcrypt-2.5.7

hth, steve
herowekker at hotmail dot com 31-Jul-2003 05:55
mcrypt_ecb with base64_decode gave some problems, i found out that it had to be chopped to work:

<?php
chop
(mcrypt_ecb(MCRYPT_BLOWFISH,$key,base64_decode($input),MCRYPT_DECRYPT));
?>
scott at boothcreek dot com 28-Mar-2002 01:28
If you are using ECB mode to encrypt it does not seem to use the iv (initialization vector) for much of anything, given the same key it will always decrypt it no matter what the iv is.  If you use CBC mode you must decrypt with the same iv that you encrypted with.

 If you use a different iv before decrypting, your decrypt will not work.  IMHO it seems better to use CBC mode than ECB as ECB will always encrypt to the same cipher text given the same plain text  (leaving you open to know plaintext attacks).  CBC uses the random iv which means text encrypts to different things.  You probably could get the same effect from using random keys in ECB mode.

Read that in the Schneier book - Applied Cryptography (ISBN 0-471-11709-9)  This book is a must for anyone seriously using any type of encryption.
pawelNOSPAM at rsc dot pl 02-Aug-2001 06:37
If you compiled mcrypt and php without problem, but phpinfo() shows there are no supported ciphers and modes, try to change mode to 755 on libdirs (/usr/local/libmcrypt, /usr/local/libcrypt).
mountie at paygate dot net 10-Feb-2000 05:21
the encrypted result data maybe binary data and It make errors in sql query.
so use the base64_encode/base64_decode function with mcrypt()
try below

<?php
base64_encode
(mcrypt_ecb(MCRYPT_BLOWFISH,$key,$input,MCRYPT_ENCRYPT));

mcrypt_ecb(MCRYPT_BLOWFISH,$key,base64_decode($input),MCRYPT_DECRYPT);
?>

 
show source | credits | sitemap | contact | advertising | mirror sites