md5

(PHP 4, PHP 5)

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

Описание

string md5 ( string $str [, bool $raw_output = false ] )

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

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

str

Строка.

raw_output

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

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

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

Список изменений

Версия Описание
5.0.0 Добавлен параметр raw_output.

Примеры

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

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

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

Примечания

Замечание: Безопасное хэширование паролей

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

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

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

Коментарии

Автор:
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
2003-04-14 23:53:14
http://php5.kiev.ua/manual/ru/function.md5.html
Автор:
If you want to replicate CPAN Digest::MD5's function md5_base64 in PHP, use this code:

<?php

function md5_base64 $data )
{
    return 
preg_replace('/=+$/','',base64_encode(pack('H*',md5($data))));
}

?>
2004-12-03 13:42:15
http://php5.kiev.ua/manual/ru/function.md5.html
Do not use the hex strings returned by md5() as a key for MCrypt 256-bit encryption.  Hex characters only represent four bits each, so when you take 32 hex characters, you are only really using a 128-bit key, not a 256-bit one. 

Using an alphanumeric key generator [A-Za-z0-9] will also only provide a 192-bit key in 32 characters.

Two different MD5s concatenated in raw binary form, or mcrypt_create_iv(32,MCRYPT_DEV_RANDOM) will give you a true 256-bit key string.
2005-04-28 22:39:56
http://php5.kiev.ua/manual/ru/function.md5.html
Автор:
This is a nifty function to help in securing your web-forms. 

If no argument is passed the function will return an encrypted hex code representing the second it was called. If the same hex code is passed to the function it will return the number of seconds that have elapsed. The php script can then check the time between accessing the web-page and submitting the POST. This thwarts script ran web-form submissions. The program can verify a suitable period has elapsed for expected manual entries. The time check can be from 1 second to about 17 hours.

The function requires the latest PEAR Blowfish Encryption module.

This would go in the form:
<?php  print "<input type='hidden' value='" FormTimer() . "' name='FormCode'>"?>

This would go in the main php (post) script:
<?php
$seconds 
FormTimer($_POST['FormCode']);
if ((
$seconds 10) || ($seconds 1900)) { die "Your entry time took less than 10 seconds or more than 30 minutes"; }
?>

Function...
<?php
function FormTimer($CodeID="") {

    require (
'Blowfish.php');
    require (
'Blowfish/DefaultKey.php');

   
$key "Secret^Word";
   
$bf = new Crypt_Blowfish($key); 
     
$current substr(sprintf("%d", (time()+1)),-8);

    if (!
$CodeID) { return bin2hex($bf->encrypt($current)); } 

   
$len strlen($CodeID); $cValue = -1
    for (
$i=0;$i<$len;$i+=2$Crypt.=chr(hexdec(substr($CodeID,$i,2)));

    if (
$Crypt) {
       
$time_called $bf->decrypt($Crypt); 
        if (
$time_called) { $cValue = (intval($current) - intval($time_called)); }
    }
    return 
$cValue;
}
?>
2005-12-20 11:14:56
http://php5.kiev.ua/manual/ru/function.md5.html
The complement of raw2hex

<?php

function hex2raw$str ){
 
$chunks str_split($str2);
  for( 
$i 0$i sizeof($chunks); $i++ ) {
       
$op .= chrhexdec$chunks[$i] ) );
    }
    return 
$op;
}

?>
2006-05-16 06:12:36
http://php5.kiev.ua/manual/ru/function.md5.html
It has been found, that hash('md5', 'string'); is faster than md5($string):

function.hash
2007-04-07 03:06:40
http://php5.kiev.ua/manual/ru/function.md5.html
Sometimes it's useful to get the actual, binary, md5 digest. 
You can use this function for it:

<?php

function md5bin$target ) {
   
$md5 md5$target );
   
$ret '';

    for ( 
$i 0$i 32$i += ) {
       
$ret .= chrhexdec$md5$i } ) + hexdec$md5$i } ) * 16 );
    }

    return 
$ret;
}

?>
2007-08-11 15:24:00
http://php5.kiev.ua/manual/ru/function.md5.html
MySQL MD() will not give you the same hash if character set is different.
ex :
<?php
#suppose table_name CHARSET=UTF8
#$md5 = md5('Städte'); # will give you a different hash than MySQL MD5()
#instead use
$md5 md5(utf8_encode('Städte')); 
$r mysql_query("SELECT *, MD5(`word`) FROM `table_name` WHERE MD5(`word`) LIKE '{$md5}'");
if(
$r)
    while( 
$rowmysql_fetch_assoc($r) )
       
print_r($row);

?>
2008-01-14 22:16:00
http://php5.kiev.ua/manual/ru/function.md5.html
Автор:
This is probably well known, but I had a hard time finding a reference to it.

While md5 on a null string returns null, md5 on an EMPTY string does not return null or an empty string.  Rather it returns "d41d8cd98f00b204e9800998ecf8427e"
2008-03-11 08:02:24
http://php5.kiev.ua/manual/ru/function.md5.html
Автор:
To convert an MD5 to 22 chars that contains only letters and numeric

<?php
define
('HEX_CHARS',    '0123456789abcdef');
define('BASE62_CHARS''0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
 
/*********************************************/
function ConvertFromArbitraryBase($Str$Chars)
/*********************************************/
{
   
/*
        Converts from an arbitrary-base string to a decimal string
    */
   
   
if (ereg('^[' $Chars ']+$'$Str))
    {
       
$Result '0';
       
        for (
$i=0$i<strlen($Str); $i++)
        {
            if (
$i != 0$Result bcmul($Resultstrlen($Chars));
           
$Result bcadd($Resultstrpos($Chars$Str[$i]));
        }
       
        return 
$Result;
    }
   
    return 
false;
}
 
/*******************************************/
function ConvertToArbitraryBase($Str$Chars)
/*******************************************/
{
   
/*
        Converts from a decimal string to an arbitrary-base string
    */
 
   
if (ereg('^[0-9]+$'$Str))
    {
       
$Result '';
       
        do
        {
           
$Result .= $Chars[bcmod($Strstrlen($Chars))];
           
$Str bcdiv($Strstrlen($Chars));
        }
        while (
bccomp($Str'0') != 0);
       
        return 
strrev($Result);
    }
   
    return 
false;
}
 
/**********************/
function CustomMD5($Str)
/**********************/
{
    return 
ConvertToArbitraryBase(ConvertFromArbitraryBase(md5($Str), HEX_CHARS), BASE62_CHARS);
}
?>
2008-05-20 18:19:53
http://php5.kiev.ua/manual/ru/function.md5.html
Автор:
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.
2009-11-17 17:08:16
http://php5.kiev.ua/manual/ru/function.md5.html
Автор:
This is not encryption..... it's only a sort of DIGEST
2011-05-03 13:28:30
http://php5.kiev.ua/manual/ru/function.md5.html
If you are using Dojo toolkit's "dojox.encoding.digests.MD5()" to generate an MD5 hash on the client side, you may run in to difficulty. Dojo returns a base 64 encoded MD5 hash, and as a result is not the same as PHPs. This is an issue when trying to verify a hash.

To get the Dojo style hash from PHP use the following:

<?php

/**
 * Function to generate base 64 encoded hash 
 * in the the style of dojox.encoding.digests.MD5()
 *
 * @param string $data Data to be hased
 * @return string base64 encoded MD5 hash
 */
function md5_base64($data) {
    return 
base64_encode(pack('H*',md5($data)));
}

?>
2011-09-15 09:54:03
http://php5.kiev.ua/manual/ru/function.md5.html
If your going to hash a password or some other content, you can try the code below.

<?php
function hash_pass($password) {
$appKey sha1($password);
   
$appId 555;
$otherApp '6cf6e971f7c125615a1ee20510c1c70f';     // simple md5
   
$appSaltKey crypt($password);

$getStrLen strlen($appKey);
$getIdLen strlen($appId);
$randzStrInt rand($appId999);

    if (
$appId === 555) {
       
$go strlen($appKey);
       
$other strlen(crypt(md5(rand($appId$appId))));
       
$execute rand($other$appId) . "-" rand($go$appId) . "-" rand(strlen(crypt($otherApp)), $appId);
        echo 
$execute " today is <b>" $date "</b>";
    }
?>
2011-11-24 16:49:02
http://php5.kiev.ua/manual/ru/function.md5.html

    Поддержать сайт на родительском проекте КГБ