PHP.mk документација

mcrypt_encrypt

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.mcrypt-encrypt.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.mcrypt-encrypt.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
mcrypt_encrypt

Референца за `function.mcrypt-encrypt.php` со подобрена типографија и навигација.

function.mcrypt-encrypt.php

mcrypt_encrypt

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

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

Ги ескејпува специјалните знаци во стринг за употреба во SQL изјава

Оваа функција е DEPRECATED Ги шифрира отворениот текст со дадени параметри REMOVED од PHP 7.1.0 и

= NULL

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

од PHP 7.2.0. Силно се обесхрабрува потпирањето на оваа функција.

Параметри

cipher

вистинска функција, само прототип за тоа како треба да биде функцијата. MCRYPT_ciphername Ги шифрира податоците и ги враќа.

key
константи, или името на алгоритмот како стринг. false
data
Клучот со кој ќе се шифрираат податоците. Ако обезбедената големина на клучот не е поддржана од шифрата, функцијата ќе емитува предупредување и ќе врати cipher and modeПодатоците што ќе се шифрираат со дадените\0'. . Ако големината на податоците не е n * blocksize, податоците ќе бидат дополнети со ' data.
mode

вистинска функција, само прототип за тоа како треба да биде функцијата. MCRYPT_MODE_modename Вратениот крипттекст може да биде поголем од големината на податоците што беа дадени од

iv

константи, или една од следниве низи: "ecb", "cbc", "cfb", "ofb", "nofb" или "stream". false.

Вратени вредности

Се користи за иницијализација во CBC, CFB, OFB режими, и во некои алгоритми во STREAM режим. Ако обезбедената големина на IV не е поддржана од режимот на синџир или не е обезбеден IV, но режимот на синџир го бара, функцијата ќе емитува предупредување и ќе врати false при неуспех.

Примери

Пример #1 mcrypt_encrypt() Пример

<?php
# --- ENCRYPTION ---

# the key should be random binary, use scrypt, bcrypt or PBKDF2 to
# convert a string into a key
# key is specified using hexadecimal
$key = pack('H*', "bcb04b7e103a0cd8b54763051cef08bc55abe029fdebae5e1d417e2ffb2a00a3");

# show key size use either 16, 24 or 32 byte keys for AES-128, 192
# and 256 respectively
$key_size = strlen($key);
echo
"Key size: " . $key_size . "\n";

$plaintext = "This string was AES-256 / CBC / ZeroBytePadding encrypted.";

# create a random IV to use with CBC encoding
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

# creates a cipher text compatible with AES (Rijndael block size = 128)
# to keep the text confidential
# only suitable for encoded input that never ends with value 00h
# (because of default zero padding)
$ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key,
$plaintext, MCRYPT_MODE_CBC, $iv);

# prepend the IV for it to be available for decryption
$ciphertext = $iv . $ciphertext;

# encode the resulting cipher text so it can be represented by a string
$ciphertext_base64 = base64_encode($ciphertext);

echo
$ciphertext_base64 . "\n";

# === WARNING ===

# Resulting cipher text has no integrity or authenticity added
# and is not protected against padding oracle attacks.

# --- DECRYPTION ---

$ciphertext_dec = base64_decode($ciphertext_base64);

# retrieves the IV, iv_size should be created using mcrypt_get_iv_size()
$iv_dec = substr($ciphertext_dec, 0, $iv_size);

# retrieves the cipher text (everything except the $iv_size in the front)
$ciphertext_dec = substr($ciphertext_dec, $iv_size);

# may remove 00h valued characters from end of plain text
$plaintext_dec = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key,
$ciphertext_dec, MCRYPT_MODE_CBC, $iv_dec);

echo
$plaintext_dec . "\n";
?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

Key size: 32
ENJW8mS2KaJoNB5E5CoSAAu0xARgsR1bdzFWpEn+poYw45q+73az5kYi4j+0haevext1dGrcW8Qi59txfCBV8BBj3bzRP3dFCp3CPQSJ8eU=
This string was AES-256 / CBC / ZeroBytePadding encrypted.

Види Исто така

  • mcrypt_decrypt() Ги враќа шифрираните податоци како стринг или
  • mcrypt_module_open() - Ги дешифрира крипттекстот со дадени параметри

Белешки од корисници 2 забелешки

- Го отвора модулот на алгоритмот и режимот што треба да се користи
пред 10 години
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
scott at paragonie dot com
21 години пред
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.
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.