md5

(PHP 4, PHP 5, PHP 7, PHP 8)

md5Возвращает MD5-хеш строки

Внимание

Не рекомендуется использовать эту функцию для безопасного хранения паролей ввиду высокой скорости работы этого алгоритма. Подробнее об этом рассказано в разделе «Ответы на часто задаваемые вопросы по хешированию паролей».

Описание

md5(string $string, bool $binary = false): string

Вычисляет MD5-хеш строки string, используя » алгоритм MD5 RSA Data Security, Inc. и возвращает этот хеш.

Список параметров

string

Строка.

binary

Если необязательный аргумент binary имеет значение true, то возвращается бинарная строка из 16 символов.

Возвращаемые значения

Возвращает хеш в виде 32-символьного шестнадцатеричного числа.

Примеры

Пример #1 Пример использования md5()

<?php
$str
= 'яблоко';

if (
md5($str) === '1afa148eb41f2e7103f21410bf48346c') {
echo
"Вам зелёное или красное яблоко?";
}
?>

Смотрите также

  • md5_file() - Возвращает MD5-хеш файла
  • sha1_file() - Возвращает SHA1-хеш файла
  • crc32() - Вычисляет полином CRC32 для строки
  • sha1() - Возвращает SHA1-хеш строки
  • hash() - Генерирует хеш-код (подпись сообщения)
  • crypt() - Необратимое хеширование строки
  • password_hash() - Создаёт хеш пароля

add a note add a note

User Contributed Notes 7 notes

up
7
yiminrong at yahoo dot ca
3 years ago
Regarding Ray Paseur's comment, the strings hash to:

0e462097431906509019562988736854
0e830400451993494058024219903391

The odds of getting a hash exactly matching the format /^0+e[0-9]+$/ are not high but are also not negligible.

It should be added as a general warning for all hash functions to always use the triple equals === for comparison.

Actually, the warning should be in the operators section when comparing string values! There are lots of warnings about string comparisons, but nothing specific about the format /^0+e[0-9]+$/.
up
3
Ray.Paseur sometimes uses Gmail
6 years ago
md5('240610708') == md5('QNKCDZO')

This comparison is true because both md5() hashes start '0e' so PHP type juggling understands these strings to be scientific notation.  By definition, zero raised to any power is zero.
up
-25
John
15 years ago
If you want to hash a large amount of data you can use the hash_init/hash_update/hash_final functions.

This allows you to hash chunks/parts/incremental or whatever you like to call it.
up
-26
Steve M
4 years ago
I've found multiple sites suggesting the code:

md5(file_get_contents($filename));

Until recently, I hadn't noticed any issues with this locally... but then I tried to hash a 700MB file, with a 2048MB memory limit and kept getting out of memory errors...

There appears to be a limit to how long a string the md5() function can handle, and the alternative function is likely more memory efficient anyway. I would highly recommend to all who need file hashing (for detecting duplicates, not security digests) use the md5_file() function and NOT the regular string md5() function!

md5_file($filename);

Note, to those interested, as this was for a local application not a server, I was more concerned with results than memory efficiency. In a live environment, you would never want to read an entire file into memory at once when avoidable. (at the time of coding, I did not know of the alternative function)
up
-35
Shane Allen
21 years ago
From the documentation on Digest::MD5:
md5($data,...)
This function will concatenate all arguments, calculate the MD5 digest of this "message", and return it in binary form.

md5_hex($data,...)
Same as md5(), but will return the digest in hexadecimal form.

PHP's function returns the digest in hexadecimal form, so my guess is that you're using md5() instead of md5_hex(). I have verified that md5_hex() generates the same string as PHP's md5() function.

(original comment snipped in various places)
>Hexidecimal hashes generated with Perl's Digest::MD5 module WILL
>NOT equal hashes generated with php's md5() function if the input
>text contains any non-alphanumeric characters.
>
>$phphash = md5('pa$$');
>echo "php original hash from text: $phphash";
>echo "md5 hash from perl: " . $myrow['password'];
>
>outputs:
>
>php original hash from text: 0aed5d740d7fab4201e885019a36eace
>hash from perl: c18c9c57cb3658a50de06491a70b75cd
up
-38
radon8472 at radon-software dot net
8 years ago
<?php
   
function raw2hex($rawBinaryChars)
    {
      return =
array_pop(unpack('H*', $rawBinaryChars));
    }
?>

The complement of hey2raw.
You can use to convert from raw md5-format to human-readable format.

This can be usefull to check "Content-Md5" HTTP-Header.

<?php
  $rawMd5   
= base64_decode($_SERVER['HTTP_CONTENT_MD5']);
 
$post_data = file_get_contents("php://input");

  if(
raw2hex($rawMd5) == md5($post_data)) // Post-Data is okay
 
else                                    // Post-Data is currupted
?>
up
-37
hkmaly
7 years ago
Note: Before you get some idea like using md5 with password as way to prevent others tampering with message, read pages "Length extension attack" and "Hash-based message authentication code" on wikipedia. In short, naive constructions can be dangerously insecure. Use hash_hmac if available or reimplement HMAC properly without shortcuts.
To Top