mcrypt_encrypt

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_encrypt -- Encrypts plaintext with given parameters

Description

string mcrypt_encrypt ( string cipher, string key, string data, string mode [, string iv] )

mcrypt_encrypt() encrypts the data and returns the encrypted data.

Cipher is one of the MCRYPT_ciphername constants of the name of the algorithm as string.

Key is the key with which the data will be encrypted. If it's smaller that the required keysize, it is padded with '\0'. It is better not to use ASCII strings for keys. It is recommended to use the mhash functions to create a key from a string.

Data is the data that will be encrypted with the given cipher and mode. If the size of the data is not n * blocksize, the data will be padded with '\0'. The returned crypttext can be larger that the size of the data that is given by data.

Mode is one of the MCRYPT_MODE_modename constants of one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".

The IV parameter is used for the initialisation in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If you do not supply an IV, while it is needed for an algorithm, the function issues a warning and uses an IV with all bytes set to '\0'.

例子 1. mcrypt_encrypt() Example

<?php
    $iv_size
= mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
    
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    
$key = "This is a very secret key";
    
$text = "Meet me at 11 o'clock behind the monument.";
    echo
strlen($text) . "\n";

    
$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv);
    echo
strlen($crypttext) . "\n";
?>

上例将输出:

42
64

See also mcrypt_module_open() for a more advanced API and an example.


add a note add a note User Contributed Notes
alexandrub83 at yahoo dot com
25-Sep-2005 09:53
A class to encrypt, decrypt data! if you have problems with using it please visit my site http://www.alexandrub.tk and mail me using Contact section! I use it to encrypt POST and GET data! I don't remember his name but thanks to how recognize his code in the binFromHex function!

<?php
//copyright www.alexandrub.tk
//ver 1.00
class cript
{
var
$key;
var
$td;
var
$time4keyToChange;
var
$iv;

function
cript($aKey='time',$aTime4keyToChange=3600)
 {
 
$this->time4keyToChange=$aTime4keyToChange;
 if(
$aKey!='time')
   {
  
$this->key=$aKey."&".intval(time()/$this->time4keyToChange);
   }
   else
   {
  
$this->key=intval(time()/$this->time4keyToChange);
   }
 
$this->td = MCRYPT_RIJNDAEL_256;
 
$this->iv = "qe3jigneqfrgnqw2egfmas4qetjkn5lg";
 }

function
hexFromBin($data)
{
return
bin2hex($data);
}

function
binFromHex($data)
 {
 
$len = strlen($data);
 return
pack("H" . $len, $data);
 }

function
criptData($data)
 {
 return
$this->hexFromBin(mcrypt_encrypt($this->td, $this->key, $data, MCRYPT_MODE_CBC, $this->iv));
 }
function
decriptData($eData)
 {
 return
trim(mcrypt_decrypt($this->td, $this->key, $this->binFromHex($eData), MCRYPT_MODE_CBC, $this->iv));
 }
}
return
true;
?>
jesse at pctest dot com
08-Dec-2004 06:43
Solving 3DES incompatibilities with .NET's TripleDESCryptoServiceProvider

mcrypt's 3DES only accepts 192 bit keys, but Microsoft's .NET and many other tools accept both 128 and 192 bit keys.
If your key is too short, mcrypt will 'helpfully' pad null characters onto the end, but .NET refuses to use a key where the last third is all null (this is a Bad Key). This prevents you from emulating mcrypt's "short key" behaviour in .NET.

How to reconcile this? A little DES theory is in order
3DES runs the DES algorithm three times, using each third of your 192 bit key as the 64 bit DES key

Encrypt Key1 -> Decrypt Key2 -> Encrypt Key3

and both .NET and PHP's mcrypt do this the same way.
The problem arises in short key mode on .NET, since 128 bits is only two 64 bit DES keys
The algorithm that they use then is:

Encrypt Key1 -> Decrypt Key2 -> Encrypt Key1

mcrypt does not have this mode of operation natively.
but before you go and start running DES three times yourself, here's a Quick Fix
<?php
$my_key
= "12345678abcdefgh"; // a 128 bit (16 byte) key
$my_key .= substr($my_key,0,8); // append the first 8 bytes onto the end
$secret = mcrypt_encrypt(MCRYPT_3DES, $my_key, $data, MCRYPT_MODE_CBC, $iv);  //CBC is the default mode in .NET
?>

And, like magic, it works.

There's one more caveat: Data padding
mcrypt always pads data will the null character
but .NET has two padding modes: "Zeros" and "PKCS7"
Zeros is identical to the mcrypt scheme, but PKCS7 is the default.
PKCS7 isn't much more complex, though:
instead of nulls, it appends the total number of padding bytes (which means, for 3DES, it can be a value from 0x01 to 0x07)
if your plaintext is "ABC", it will be padded into:
0x41 0x42 0x43 0x05 0x05 0x05 0x05 0x05

You can remove these from a decrypted string in PHP by counting the number of times that last character appears, and if it matches it's ordinal value, truncating the string by that many characters:
<?php
   $block
= mcrypt_get_block_size('tripledes', 'cbc');
  
$packing = ord($text{strlen($text) - 1});
   if(
$packing and ($packing < $block)){
     for(
$P = strlen($text) - 1; $P >= strlen($text) - $packing; $P--){
   if(
ord($text{$P}) != $packing){
    
$packing = 0;
   }
     }
   }
  
$text = substr($text,0,strlen($text) - $packing);
?>

And to pad a string that you intend to decrypt with .NET, just add the chr() value of the number of padding bytes:
<?php
   $block
= mcrypt_get_block_size('tripledes', 'cbc');
  
$len = strlen($dat);
  
$padding = $block - ($len % $block);
  
$dat .= str_repeat(chr($padding),$padding);
?>

That's all there is to it.
Knowing this, you can encrypt, decrypt, and duplicate exactly any .NET 3DES behaviour in PHP.
cleong at nflc dot org
04-Dec-2004 06:04
Note that the key need to be a binary string--not a hex string. A 128-bit key would be 16 characters long, for example.

Use the pack() function to quickly convert a hex string into the actual binary data:

$key_hex = '66e94bd4ef8a2c3b884cfa59ca342b2e';
$key_bin = pack('H*', $key_hex);
$pt = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key_bin, $et, MCRYPT_MODE_ECB);
chris at TRIMTHIS dot chriscodes dot com
14-Aug-2004 10:31
[Editor's note: original script posted by
andrewcare at execulink dot com
07-Jul-2004 04:45]

I needed to add
trim($data)
to andrew's example for it to remove some leftover hex garbage from the decrypted string.

Here's the working example:
<?php
$data
= "Plaintext"; // Data to encrypt (http://www.ciphersbyritter.com/glossary.htm#Encryption)
$key = "Secret"; // Encryption key (http://www.ciphersbyritter.com/glossary.htm#Key)
$td = MCRYPT_RIJNDAEL_256; // Encryption cipher (http://www.ciphersbyritter.com/glossary.htm#Cipher)

$iv_size = mcrypt_get_iv_size($td, MCRYPT_MODE_ECB); // Dependant on cipher/mode combination (http://www.php.net/manual/en/function.mcrypt-get-iv-size.php)
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); // Creates an IV (http://www.ciphersbyritter.com/glossary.htm#IV)

echo "Original data: $data<br />";

$encrypted_data = mcrypt_encrypt($td, $key, $data, MCRYPT_MODE_CBC, $iv); // Encrypts data (http://www.php.net/manual/en/function.mcrypt-encrypt.php)

echo "Encrypted data: " . bin2hex($encrypted_data)  . "<br />"; // bin2hex to compensate for random character values

$data = mcrypt_decrypt($td, $key, $encrypted_data, MCRYPT_MODE_CBC, $iv); // Decrypts data (http://www.php.net/manual/en/function.mcrypt-decrypt.php)

echo trim($data);
?>

Thanks andrew, you saved me some time! Hope this saves someone else!