Php md5 всех файлов

PHP md5_file() Function

The md5_file() function calculates the MD5 hash of a file.

The md5_file() function uses the RSA Data Security, Inc. MD5 Message-Digest Algorithm.

From RFC 1321 — The MD5 Message-Digest Algorithm: «The MD5 message-digest algorithm takes as input a message of arbitrary length and produces as output a 128-bit «fingerprint» or «message digest» of the input. The MD5 algorithm is intended for digital signature applications, where a large file must be «compressed» in a secure manner before being encrypted with a private (secret) key under a public-key cryptosystem such as RSA.»

To calculate the MD5 hash of a string, use the md5() function.

Syntax

Parameter Values

Technical Details

Return Value: Returns the calculated MD5 hash on success, or FALSE on failure
PHP Version: 4.2.0+
Changelog: The raw parameter was added in PHP 5.0

More Examples

Example

Store the MD5 hash of «test.txt» in a file:

Test if «test.txt» has been changed (that is if the MD5 hash has been changed):

$md5file = file_get_contents(«md5file.txt»);
if (md5_file(«test.txt») == $md5file)
echo «The file is ok.»;
>
else
echo «The file has been changed.»;
>
?>

The output of the code above could be:

Источник

md5_file

Вычисляет MD5-хеш файла, имя которого задано аргументом filename , используя » алгоритм MD5 RSA Data Security, Inc. и возвращает этот хеш. Хеш представляет собой 32-значное шестнадцатеричное число.

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

Если имеет значение true , то возвращается бинарная строка из 16 символов.

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

Возвращает строку в случае успешного выполнения, иначе false .

Примеры

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

echo ‘MD5-хеш файла ‘ . $file . ‘: ‘ . md5_file ( $file );
?>

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

  • md5() — Возвращает MD5-хеш строки
  • sha1_file() — Возвращает SHA1-хеш файла
  • crc32() — Вычисляет полином CRC32 для строки

User Contributed Notes 5 notes

If you just need to find out if two files are identical, comparing file hashes can be inefficient, especially on large files. There’s no reason to read two whole files and do all the math if the second byte of each file is different. If you don’t need to store the hash value for later use, there may not be a need to calculate the hash value just to compare files. This can be much faster:

if( files_identical ( ‘file1.txt’ , ‘file2.txt’ ))
echo ‘files identical’ ;
else
echo ‘files not identical’ ;

// pass two file names
// returns TRUE if files are the same, FALSE otherwise
function files_identical ( $fn1 , $fn2 ) if( filetype ( $fn1 ) !== filetype ( $fn2 ))
return FALSE ;

if( filesize ( $fn1 ) !== filesize ( $fn2 ))
return FALSE ;

if(! $fp1 = fopen ( $fn1 , ‘rb’ ))
return FALSE ;

if(! $fp2 = fopen ( $fn2 , ‘rb’ )) fclose ( $fp1 );
return FALSE ;
>

$same = TRUE ;
while (! feof ( $fp1 ) and ! feof ( $fp2 ))
if( fread ( $fp1 , READ_LEN ) !== fread ( $fp2 , READ_LEN )) $same = FALSE ;
break;
>

if( feof ( $fp1 ) !== feof ( $fp2 ))
$same = FALSE ;

It’s faster to use md5sum than openssl md5:

$file_path = ‘../backup_file1.tar.gz’ ;
$result = explode ( » » , exec ( «md5sum $file_path » ));
echo «Hash keyword»>. $result [ 0 ]. «
» ;

# Here 7 other big files (20-300 MB)

$end = microtime ( true ) — $begin ;
echo «Time = $end » ;
# Time = 4.4475841522217

#Method with openssl
# Time = 12.1463856900543
?>

About 3x faster

In response to using exec instead for performance (Nov 13 2007 post), It looks like the performance depends on the size of the file. See the results below using the same script from the original post. The first hash is with md5_file and the second is with openssl md5.

With a 1MB file:
Hash = df1555ec0c2d7fcad3a03770f9aa238a; time = 0.005006
Hash = df1555ec0c2d7fcad3a03770f9aa238a; time = 0.01498

Hash = 4387904830a4245a8ab767e5937d722c; time = 0.010393
Hash = 4387904830a4245a8ab767e5937d722c; time = 0.016691

Hash = b89f948e98f3a113dc13fdbd3bdb17ef; time = 0.241907
Hash = b89f948e98f3a113dc13fdbd3bdb17ef; time = 0.037597

Performance seems to change proportionally with the file size. Judging from the previous post’s default file name (.mov) he/she was probably dealing with a large file. These are just quick tests and far from a perfect benchmark, but you might want to test your own files before assuming that the openssl solution is faster (ie, if working with small text files vs. movies, etc)

Источник

Php md5 всех файлов

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

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

Описание

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

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

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

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

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

Примеры

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

if ( md5 ( $str ) === ‘1afa148eb41f2e7103f21410bf48346c’ ) echo «Вам зелёное или красное яблоко?» ;
>
?>

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

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

User Contributed Notes 7 notes

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.

Regarding Ray Paseur’s comment, the strings hash to:

The odds of getting a hash exactly matching the format /^0+e3+$/ 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+e7+$/.

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.

I’ve found multiple sites suggesting the code:

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!

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)

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

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.

$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
?>

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.

Источник

Читайте также:  Поиск собственных значений матрицы питон
Оцените статью