PHP Conference Kansai 2025

mcrypt_encrypt

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_encryptCifra un texto

Advertencia

Esta función ha sido declarada OBSOLETA a partir de PHP 7.1.0 y será ELIMINADA a partir de PHP 7.2.0. Su uso está totalmente desaconsejado.

Descripción

mcrypt_encrypt(
    string $cipher,
    string $key,
    string $data,
    string $mode,
    string $iv = ?
): string|false

mcrypt_encrypt() cifra los datos y devuelve los datos cifrados.

Parámetros

cipher

Una de las constantes MCRYPT_nombredelcifrado, o el nombre del algoritmo como string.

key

La clave con la que se cifrarán los datos. Si el tamaño de la clave proporcionada no es compatible con el cipher, la función emitirá un warning y devolverá false

data

Los datos que se cifrarán, con el cipher y el mode indicado. Si el tamaño de los datos no es un múltiplo del tamaño de bloque, los datos se rellenarán con caracteres '\0', según sea necesario.

El texto cifrado devuelto puede ser más largo que el tamaño de los datos pasados como argumento a través de data.

mode

Una de las constantes MCRYPT_MODE_nombredelmodo, o una de las siguientes strings: "ecb", "cbc", "cfb", "ofb", "nofb" o "stream".

iv

Utilizado para la inicialización en los modos CBC, CFB, OFB, y en algunos algoritmos en el modo STREAM. Si el tamañlo del IV proporcionado no está soportado por el modo de encadenamiento o no se proporcionó ninún IV, y el modo de encadenamiento requiere uno, la función emitirá una advertencia y devolverá false.

Valores devueltos

Devuelve los datos cifrados, como string o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo con mcrypt_encrypt()

<?php
# --- CIFRADO ---

# la clave debería ser un binario aleatorio, utilice la función scrypt, bcrypt
# o PBKDF2 para convertir una cadena de caracteres en una clave.
# La clave se especifica utilizando notación hexadecimal.
$key = pack('H*', "bcb04b7e103a0cd8b54763051cef08bc55abe029fdebae5e1d417e2ffb2a00a3");

# Muestra el tamaño de la clave utilizada; claves de 16, 24 o 32 bytes para
# AES-128, 192 y 256 respectivamente.
$key_size = strlen($key);
echo
"Tamaño de la clave: " . $key_size . "\n";

$plaintext = "Esta cadena de caracteres ha sido cifrada en AES-256 / CBC / ZeroBytePadding.";

# Crea un IV aleatorio para usar con el cifrado CBC
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

# Crea un texto cifrado compatible con AES (Rijndael block size = 128)
# para mantener el texto confidencial.
# Solo aplicable para entradas codificadas que nunca terminan
# con el valor 00h (debido a la eliminación predeterminada de ceros finales)
$ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key,
$plaintext, MCRYPT_MODE_CBC, $iv);

# Se añade el IV al inicio del texto cifrado para hacerlo disponible para el descifrado
$ciphertext = $iv . $ciphertext;

# Codifica el texto cifrado resultante para que pueda ser representado por una cadena de caracteres
$ciphertext_base64 = base64_encode($ciphertext);

echo
$ciphertext_base64 . "\n";

# === ADVERTENCIA ===

# El texto cifrado resultante no contiene integridad ni autenticación
# y no está protegido contra ataques de tipo "oracle padding".

# --- DESCIFRADO ---

$ciphertext_dec = base64_decode($ciphertext_base64);

# Obtiene el IV, iv_size debe haber sido creado utilizando la función
# mcrypt_get_iv_size()
$iv_dec = substr($ciphertext_dec, 0, $iv_size);

# Obtiene el texto del cipher (todo, excepto $iv_size del inicio)
$ciphertext_dec = substr($ciphertext_dec, $iv_size);

# Se deben eliminar los caracteres de valor 00h del final del texto plano
$plaintext_dec = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key,
$ciphertext_dec, MCRYPT_MODE_CBC, $iv_dec);

echo
$plaintext_dec . "\n";
?>

El resultado del ejemplo sería:

Tamaño de la clave: 32
ENJW8mS2KaJoNB5E5CoSAAu0xARgsR1bdzFWpEn+poYw45q+73az5kYi4j+0haevext1dGrcW8Qi59txfCBV8BBj3bzRP3dFCp3CPQSJ8eU=
Esta cadena de caracteres ha sido cifrada en AES-256 / CBC / ZeroBytePadding.

Ver también

add a note

User Contributed Notes 2 notes

up
63
scott at paragonie dot com
9 years ago
If you're writing code to encrypt/encrypt data in 2015, you should use openssl_encrypt() and openssl_decrypt(). The underlying library (libmcrypt) has been abandoned since 2007, and performs far worse than OpenSSL (which leverages AES-NI on modern processors and is cache-timing safe).

Also, MCRYPT_RIJNDAEL_256 is not AES-256, it's a different variant of the Rijndael block cipher. If you want AES-256 in mcrypt, you have to use MCRYPT_RIJNDAEL_128 with a 32-byte key. OpenSSL makes it more obvious which mode you are using (i.e. 'aes-128-cbc' vs 'aes-256-ctr').

OpenSSL also uses PKCS7 padding with CBC mode rather than mcrypt's NULL byte padding. Thus, mcrypt is more likely to make your code vulnerable to padding oracle attacks than OpenSSL.

Finally, if you are not authenticating your ciphertexts (Encrypt Then MAC), you're doing it wrong.

Further reading:

https://paragonie.com/blog/2015/05/using-encryption-and-authentication-correctly

https://paragonie.com/blog/2015/05/if-you-re-typing-word-mcrypt-into-your-code-you-re-doing-it-wrong
up
24
jesse at pctest dot com
20 years ago
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.
To Top