PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  
<mcal_week_of_yearmcrypt_cbc>
view the version of this page
Last updated: Sun, 02 May 2004

LV. Mcrypt Encryption Functions

Introduzione

This is an interface to the mcrypt library, which supports a wide variety of block algorithms such as DES, TripleDES, Blowfish (default), 3-WAY, SAFER-SK64, SAFER-SK128, TWOFISH, TEA, RC2 and GOST in CBC, OFB, CFB and ECB cipher modes. Additionally, it supports RC6 and IDEA which are considered "non-free".

Requisiti

These functions work using mcrypt. To use it, download libmcrypt-x.x.tar.gz from http://mcrypt.sourceforge.net/ and follow the included installation instructions. Windows users will find all the needed compiled mcrypt binaries at http://ftp.emini.dk/pub/php/win32/mcrypt/.

If you linked against libmcrypt 2.4.x or higher, the following additional block algorithms are supported: CAST, LOKI97, RIJNDAEL, SAFERPLUS, SERPENT and the following stream ciphers: ENIGMA (crypt), PANAMA, RC4 and WAKE. With libmcrypt 2.4.x or higher another cipher mode is also available; nOFB.

Installazione

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.

Configurazione di Runtime

Il comportamento di queste funzioni č influenzato dalle impostazioni di php.ini.

Tabella 1. Mcrypt configuration options

NameDefaultChangeable
mcrypt.algorithms_dirNULLPHP_INI_ALL
mcrypt.modes_dirNULLPHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.

Costanti predefinite

Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione č stata compilata nel PHP o se č stata caricata dinamicamente a runtime.

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)

Mcrypt ciphers

Here is a list of ciphers which are currently supported by the mcrypt extension. For a complete list of supported ciphers, see the defines at the end of mcrypt.h. The general rule with the mcrypt-2.2.x API is that you can access the cipher from PHP with MCRYPT_ciphername. With the libmcrypt-2.4.x and libmcrypt-2.5.x API these constants also work, but it is possible to specify the name of the cipher as a string with a call to mcrypt_module_open().

  • MCRYPT_3DES

  • MCRYPT_ARCFOUR_IV (libmcrypt > 2.4.x only)

  • MCRYPT_ARCFOUR (libmcrypt > 2.4.x only)

  • MCRYPT_BLOWFISH

  • MCRYPT_CAST_128

  • MCRYPT_CAST_256

  • MCRYPT_CRYPT

  • MCRYPT_DES

  • MCRYPT_DES_COMPAT (libmcrypt 2.2.x only)

  • MCRYPT_ENIGMA (libmcrypt > 2.4.x only, alias for MCRYPT_CRYPT)

  • MCRYPT_GOST

  • MCRYPT_IDEA (non-free)

  • MCRYPT_LOKI97 (libmcrypt > 2.4.x only)

  • MCRYPT_MARS (libmcrypt > 2.4.x only, non-free)

  • MCRYPT_PANAMA (libmcrypt > 2.4.x only)

  • MCRYPT_RIJNDAEL_128 (libmcrypt > 2.4.x only)

  • MCRYPT_RIJNDAEL_192 (libmcrypt > 2.4.x only)

  • MCRYPT_RIJNDAEL_256 (libmcrypt > 2.4.x only)

  • MCRYPT_RC2

  • MCRYPT_RC4 (libmcrypt 2.2.x only)

  • MCRYPT_RC6 (libmcrypt > 2.4.x only)

  • MCRYPT_RC6_128 (libmcrypt 2.2.x only)

  • MCRYPT_RC6_192 (libmcrypt 2.2.x only)

  • MCRYPT_RC6_256 (libmcrypt 2.2.x only)

  • MCRYPT_SAFER64

  • MCRYPT_SAFER128

  • MCRYPT_SAFERPLUS (libmcrypt > 2.4.x only)

  • MCRYPT_SERPENT(libmcrypt > 2.4.x only)

  • MCRYPT_SERPENT_128 (libmcrypt 2.2.x only)

  • MCRYPT_SERPENT_192 (libmcrypt 2.2.x only)

  • MCRYPT_SERPENT_256 (libmcrypt 2.2.x only)

  • MCRYPT_SKIPJACK (libmcrypt > 2.4.x only)

  • MCRYPT_TEAN (libmcrypt 2.2.x only)

  • MCRYPT_THREEWAY

  • MCRYPT_TRIPLEDES (libmcrypt > 2.4.x only)

  • MCRYPT_TWOFISH (for older mcrypt 2.x versions, or mcrypt > 2.4.x )

  • MCRYPT_TWOFISH128 (TWOFISHxxx are available in newer 2.x versions, but not in the 2.4.x versions)

  • MCRYPT_TWOFISH192

  • MCRYPT_TWOFISH256

  • MCRYPT_WAKE (libmcrypt > 2.4.x only)

  • MCRYPT_XTEA (libmcrypt > 2.4.x only)

You must (in CFB and OFB mode) or can (in CBC mode) supply an initialization vector (IV) to the respective cipher function. The IV must be unique and must be the same when decrypting/encrypting. With data which is stored encrypted, you can take the output of a function of the index under which the data is stored (e.g. the MD5 key of the filename). Alternatively, you can transmit the IV together with the encrypted data (see chapter 9.3 of Applied Cryptography by Schneier (ISBN 0-471-11709-9) for a discussion of this topic).

Esempi

Mcrypt can be used to encrypt and decrypt using the above mentioned ciphers. If you linked against libmcrypt-2.2.x, the four important mcrypt commands (mcrypt_cfb(), mcrypt_cbc(), mcrypt_ecb(), and mcrypt_ofb()) can operate in both modes which are named MCRYPT_ENCRYPT and MCRYPT_DECRYPT, respectively.

Esempio 1. Encrypt an input value with TripleDES under 2.2.x in ECB mode

<?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);
?>
This example will give you the encrypted data as a string in $encrypted_data.

If you linked against libmcrypt 2.4.x or 2.5.x, these functions are still available, but it is recommended that you use the advanced functions.

Esempio 2. Encrypt an input value with TripleDES under 2.4.x and higher in ECB mode

<?php
   $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);
?>
This example will give you the encrypted data as a string in $encrypted_data. For a full example see mcrypt_module_open().

Sommario
mcrypt_cbc -- Encrypt/decrypt data in CBC mode
mcrypt_cfb -- Encrypt/decrypt data in CFB mode
mcrypt_create_iv --  Create an initialization vector (IV) from a random source
mcrypt_decrypt -- Decrypts crypttext with given parameters
mcrypt_ecb -- Deprecated: Encrypt/decrypt data in ECB mode
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 -- Get the block size of the specified cipher
mcrypt_get_cipher_name -- Get the name of the specified cipher
mcrypt_get_iv_size --  Returns the size of the IV belonging to a specific cipher/mode combination
mcrypt_get_key_size -- Get the key size of the specified cipher
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 -- Encrypt/decrypt data in OFB mode
mdecrypt_generic -- Decrypt data


add a note add a note User Contributed Notes
Mcrypt Encryption Functions
dzelko at hotmail dot com
14-May-2004 06: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.
Deek Starr
21-Apr-2004 09:16
As per the issue with decrypting (mdecrypt_generic) on iss in windows. My finding as that the new 2004 version works but the 2002 does not.

I'm using WinXP Server 2003 - ISS 6.0 with:

libmcrypt.dll          19-Jan-2004 02:27  163k
http://ftp.emini.dk/pub/php/win32/mcrypt/libmcrypt.dll

php_mycrypt.dll      14-Jan-2004 5:34    36.8k
From the v4.3.6 windows zip distribution of php.
http://www.php.net/get/php-4.3.6-Win32.zip/from/a/mirror

My assumption is that the new IIS 6 should use the new libmcrypt where IIS <= 5 should use the older version.

[ Hope that helps ]
dmichel at earthlink dot net
14-Apr-2004 04:34
I'll vouch for Jonathan's note below.  I'm using IIS and win2k.  I downloaded the dll from the link at the top of the page and experienced problems when trying to decrypt.  The binaries at http://ftp.proventum.net/pub/php/win32/misc/mcrypt/ (libmcrypt.dll 12/30/2002 254K) work for IIS.  This zip also has you replace php_mcrypt.dll which it contains.  Don't use the dll from http://ftp.emini.dk/pub/php/win32/mcrypt/ (libmcrypt.dll 19-Jan-2004 02:27  163k).
Jonathon Freeman
17-Mar-2004 07:00
If you're a Windows user you might be having trouble getting Mcrypt up and going. This is what I did, and it worked perfectly:

1. Download the latest binaries from http://ftp.proventum.net/pub/php/win32/misc/mcrypt/. At the the time of this writing, the link at the top of this page doesn't have everything you need.
2. Unzip the file, then follow the instructions in README.txt.
3. Restart Apache, and viola!

Hope that helps someone...
robert at peakepro dot com
02-Mar-2004 08:59
I have ammended the mcrypt_check_sanity() function. This is a bug fix: the function was reinitializing the IV, which is unacceptable. Here is the complete, fixed version. Note that 'stream' mode is not tested.

<?PHP
/* run a self-test through every listed cipher and mode */
function mcrypt_check_sanity() {
$modes = mcrypt_list_modes();
$algorithms = mcrypt_list_algorithms();

 foreach (
$algorithms as $cipher) {
   if(
mcrypt_module_self_test($cipher)) {
       print
$cipher." ok.<br />\n";
   } else {
       print
$cipher." not ok.<br />\n";
   }
   foreach (
$modes as $mode) {
       if(
$mode == 'stream') {
          
$result = "not tested";
       } else if(
mcrypt_test_module_mode($cipher,$mode)) {
            
$result = "ok";
       } else {
            
$result = "not ok";
       }
       print
$cipher." in mode ".$mode." ".$result."<br />\n";
        
mcrypt_module_close($td);
   }
 }
 }

// a variant on the example posted in mdecrypt_generic
function mcrypt_test_module_mode($module,$mode) {
 
/* Data */
 
$key = 'this is a very long key, even too long for the cipher';
 
$plain_text = 'very important data';

 
/* Open module, and create IV */
 
$td = mcrypt_module_open($module, '',$mode, '');
 
$key = substr($key, 0, mcrypt_enc_get_key_size($td));
 
$iv_size = mcrypt_enc_get_iv_size($td);
 
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

 
/* Initialize encryption handle */
if (mcrypt_generic_init($td, $key, $iv) != -1) {

 
/* Encrypt data */
 
$c_t = mcrypt_generic($td, $plain_text);
 
mcrypt_generic_deinit($td);
 
 
// close the module
 
mcrypt_module_close($td);

 
/* Reinitialize buffers for decryption */
 /* Open module */
 
$td = mcrypt_module_open($module, '', $mode, '');
 
$key = substr($key, 0, mcrypt_enc_get_key_size($td));

 
mcrypt_generic_init($td, $key, $iv);
 
$p_t = trim(mdecrypt_generic($td, $c_t)); //trim to remove padding

 /* Clean up */
 
mcrypt_generic_end($td);
 
mcrypt_module_close($td);
 }
 
 if (
strncmp($p_t, $plain_text, strlen($plain_text)) == 0) {
   return
TRUE;
 } else {
   return
FALSE;
 }
 }

// function call:
mcrypt_check_sanity();
?>

Apologies for any confusion the previous version may have caused. The only working mode listed was ecb, since it does not use an IV.
robert at peakepro dot com
15-Feb-2004 03:17
I found this nested loop very useful for checking the sanity of my libmcrypt install. It turned out many of the modules weren't working in certain modes. Hopefully this will save someone some frustration:

<?php

/* run a self-test through every listed cipher and mode
*/
function mcrypt_check_sanity() {
$modes = mcrypt_list_modes();
$algorithms = mcrypt_list_algorithms();

foreach (
$algorithms as $cipher) {
       if(
mcrypt_module_self_test($cipher)) {
               print
$cipher." ok.<br />\n";
       } else {
               print
$cipher." not ok.<br />\n";
       }
       foreach (
$modes as $mode) {
               if(
mcrypt_test_module_mode($cipher,$mode)) {
                      
$result = "ok";
               } else {
                      
$result = "not ok";
               }
               print
$cipher." in mode ".$mode." ".$result."<br />\n";
              
mcrypt_module_close($td);
       }
 }
}

// a variant on the example posted in mdecrypt_generic
// that works on versions of libmcrypt
// without mcrypt_generic_deinit() defined
function mcrypt_test_module_mode($module,$mode) {
 
/* Data */
 
$key = 'this is a very long key, even too long for the cipher';
 
$plain_text = 'very important data';

 
/* Open module, and create IV */
 
$td = mcrypt_module_open($module, '',$mode, '');
 
$key = substr($key, 0, mcrypt_enc_get_key_size($td));
 
$iv_size = mcrypt_enc_get_iv_size($td);
 
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

 
/* Initialize encryption handle */
if (mcrypt_generic_init($td, $key, $iv) != -1) {

 
/* Encrypt data */
 
$c_t = mcrypt_generic($td, $plain_text);
 
mcrypt_generic_end($td);
 
mcrypt_module_close($td);

 
/* Reinitialize buffers for decryption */
 /* Open module, and create IV */
 
$td = mcrypt_module_open($module, '', $mode, '');
 
$key = substr($key, 0, mcrypt_enc_get_key_size($td));
 
$iv_size = mcrypt_enc_get_iv_size($td);
 
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

 
mcrypt_generic_init($td, $key, $iv);
 
$p_t = mdecrypt_generic($td, $c_t);

 
/* Clean up */
 
mcrypt_generic_end($td);
 
mcrypt_module_close($td);
 }

if (
strncmp($p_t, $plain_text, strlen($plain_text)) == 0) {
       return
TRUE;
} else {
       return
FALSE;
}
}

// remember to call:
// mcrypt_check_sanity();
?>
mp at ecetra dot com
02-Feb-2004 11:35
i rebuilded php from sources today, the distribution was redhat el es 3. first i missed libltdl as mentioned in comment from groundzero, but the redhat has propably changed the rpm content, cause i needed libtool (libtool-lib was already installed, but was not enough). second '--disable-posix-threads' was not required: i am wondering why everybody ask for this, because i never used it and it always worked fine.

kr,
-misk
groundzero at zuavra dot net
09-Jan-2004 11: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.
20-Oct-2003 03:42
http://mcrypt.sourceforge.net/ is a good place for learning more.
simms
03-Oct-2003 08: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 voilą.
steve@itemfront dot ltd dot uk
29-Sep-2003 11: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 11:55
mcrypt_ecb with base64_decode gave some problems, i found out that it had to be chopped to work:

chop(mcrypt_ecb(MCRYPT_BLOWFISH,$key,base64_decode
($input),MCRYPT_DECRYPT));
paul at xmill dot com
05-Nov-2002 04:25
The statement that use of the 'generic' functions is 'recommended' in 2.4+ should probably be 'required'.  Having like many others struggled with a "mcrypt module initialization failed" error even when phpinfo() showed mcrypt installed and all its algorithms loaded, I found that:

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

fails, but

$td = mcrypt_module_open (MCRYPT_TripleDES, "", MCRYPT_MODE_ECB, "");
$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size ($td), MCRYPT_RAND);
mcrypt_generic_init ($td, $magic, $iv);
$key = mcrypt_generic ($td, $input);
mcrypt_generic_end ($td);

works fine.  You can't leave out the creation of the IV to the right length, even though ECB doesn't use it (happily, because I want it repeatable).
scott at boothcreek dot com
28-Mar-2002 07: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
03-Aug-2001 12: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 11: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

base64_encode(mcrypt_ecb(MCRYPT_BLOWFISH,$key,$input,MCRYPT_ENCRYPT));

mcrypt_ecb(MCRYPT_BLOWFISH,$key,base64_decode($input),MCRYPT_DECRYPT);
nsayer at quack dot kfu dot com
30-Jun-1999 01:31
For a practical example suitable for encrypting and
validating cookies or passing secure messages,
go to http://www.kfu.com/~nsayer/encryption/

<mcal_week_of_yearmcrypt_cbc>
 Last updated: Sun, 02 May 2004
show source | credits | sitemap | contact | advertising | mirror sites 
Copyright © 2001-2004 The PHP Group
All rights reserved.
This mirror generously provided by: Italia OnLine S.p.a.
Last updated: Fri May 21 04:11:23 2004 CEST