sha1

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

sha1Calculate the sha1 hash of a string

Avertizare

It is not recommended to use this function to secure passwords, due to the fast nature of this hashing algorithm. See the Password Hashing FAQ for details and best practices.

Descrierea

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

Calculates the sha1 hash of str using the » US Secure Hash Algorithm 1.

Parametri

str

The input string.

raw_output

If the optional raw_output is set to TRUE, then the sha1 digest is instead returned in raw binary format with a length of 20, otherwise the returned value is a 40-character hexadecimal number.

Valorile întoarse

Returns the sha1 hash as a string.

Exemple

Example #1 A sha1() example

<?php
$str 
'apple';

if (
sha1($str) === 'd0be2dc421be4fcd0172e5afceea3970e2f3d940') {
    echo 
"Would you like a green or red apple?";
}
?>

A se vedea și

  • sha1_file() - Calculate the sha1 hash of a file
  • crc32() - Calculates the crc32 polynomial of a string
  • md5() - Calculate the md5 hash of a string
  • hash() - Generate a hash value (message digest)
  • crypt() - One-way string hashing
  • password_hash() - Creates a password hash

add a note add a note

User Contributed Notes 31 notes

up
80
nathan
9 years ago
The suggestion below to double-hash your password is not a good idea.  You are much much better off adding a variable salt to passwords before hashing (such as the username or other field that is dissimilar for every account).

Double hashing is *worse* security than a regular hash.  What you're actually doing is taking some input $passwd, converting it to a string of exactly 32 characters containing only the characters [0-9][A-F], and then hashing *that*. You have just *greatly* increased the odds of a hash collision (ie. the odds that I can guess a phrase that will hash to the same value as your password).

sha1(md5($pass)) makes even less sense, since you're feeding in 128-bits of information to generate a 256-bit hash, so 50% of the resulting data is redundant.  You have not increased security at all.
up
11
Gregory Boshoff
11 years ago
Note that the sha1 algorithm has been compromised and is no longer being used by government agencies.

As of PHP 5.1.2 a new set of hashing functions are available.

http://www.php.net/manual/en/function.hash.php

The new function hash() supports a new range of hashing methods.

echo hash('sha256', 'The quick brown fox jumped over the lazy dog.');

It is recommended that developers start to future proof their applications by using the stronger sha-2, hashing methods such as sha256, sha384, sha512 or better.

As of PHP 5.1.2 hash_algos() returns an array of system specific or registered hashing algorithms methods that are available to PHP.

print_r(hash_algos());
up
2
marcin at marcinwolny dot net
4 years ago
Keep in mind that MD5 is less secure than SHA1.
Older CPUs can calculate MD5 over twice as fast as SHA1. GPUs in parallel calculations can handle MD5 over 3 times as fast as SHA1!

Two Radeon 79xx-series GPUs can calculate a rainbow table for 6-character lowercase MD5 password in... roughly 6 seconds!

Source: http://www.codinghorror.com/blog/2012/04/speed-hashing.html
up
2
ranko84 at gmail dot com
8 years ago
Small update..., well more like fix to the obscure function, replace
<?php
if ($keepLength != NULL)
{
    if (
$hSLength != 0)
    {
       
$hPassHash = substr($hPassHash, $hLPosition, -$hRPosition);
    }
}
?>

with

<?php
if ($keepLength != NULL)
{
    if (
$hSLength != 0)
    {
        if (
$hRPosition == 0)
        {
           
$hPassHash = substr($hPassHash, $hLPosition);
        }
        else
        {
           
$hPassHash = substr($hPassHash, $hLPosition, -$hRPosition);
        }
    }
}
?>

I've been getting few requests to explain how it's used so, this might be little long.

Problems:
1. In most solutions with hash and salt, you were bound to have one extra row in your database that would state, preferably random, salt for that hashed data. If attacker would manage to get drop of your database he would get hashed data and salt that is used with plain data to make it obscure, and then cracking that hashed data would be same as if you didn't add any salt to it.
2. I stumbled upon some functions that would hash data, then input salt into random places in hash and store it in database, but they would still have to write down random parameter used to scramble salt so they could reuse it when validating data. Getting simple database drop wouldn't help much here, but if they would manage to get their hands on obscuring function too, they could easily see what is salt and what hash.

Solutions:
1. Why use extra row to store salt when you can input it in hash. I'm not sure how attackers determine what type of hash are they facing, but I guess it has connection to hash length. In that case, why make attackers job easier and store in database data_hash+salt where they could assume just by it's length it has salt in there.
Reason behind $keepLength. If it's set to 1, strlen of hashed data plus salt would be equal to strlen of hashed data leading attacker to believe there is no salt.
If you leave $keepLength on NULL, strlen of final result would be strlen(used_hash_algorithm)+$hSLength.
$minhPass is there to reserve enough place for string that has to be hashed, so someone using this function wouldn't accidentally delete it by setting too high salt length ($hSLength), for example... if you set it 30000 it will keep working normal.

2. If you think about it, constant, but variable value when making input would be same data that is being input.
In case we're trying to hash password, and have user A with password "notme", password strlen equals to 5, and if we use default parameters of the function, with $keepLength set to 1, process would be:
random salt, hash it, add first 5 characters of hashed_salt at beginning of plain password, add last 5 characters of hashed_salt at end of plain password, hash it. Replace first 5 characters of hashed_password with first 5 character of hashed_salt, do same with last 5 characters of hashed_password, return hashed_password.
In case that string is longer than 10 characters function would use simple mathematics to reduce it to numbers lower than 10, well... lower than number that is stated in $hSLength.
And good thing is that every time user enters correct password it has same length so it's not necessary to write it anywhere.

So what is achieved in the end?
1. Attacker might not know that hash is salted, and you don't have that extra row in your database stating THIS IS SALT FOR THIS HASH.
2. If he does find out that it is, he wouldn't know what is hashed password and what is salt.
3. If he manages to get access to obscure function, only thing that might help him is value of $hSLength, where if $hSLength is set to 10 he would have to crack 10 variations of hashed string since he doesn't know how long password of user he's trying to crack is.
For example first variation would be hashed_password without last 10 characters, second variation would be hashed_password without first character and last 9 characters...
4. Even in case he has enough power to crack all 10 variations, resulting string that he might get doesn't necessarily has to be exactly long as password of original user in which case, attacker fails again.
up
2
ranko84 at gmail dot com
9 years ago
Thanks for the feedback. This should do the trick, I hope.
I think that I haven't understood this sentence completely "In this case you will need the salt to reside in the database along with the username and password." As in, were you refering to previous method, this method or this function.
Salt already resides in database along with username, password, or any string you decide to hash. This function just scrambles it depending on length of string (password) user enters so that attacker has trouble finding out what is salt and what is hash, if attacker even suspects that there is salt (reasons behind $keepLength, or defining $hSLength where you could set it to 24 leading attacker to believe he's facing sha256, not sha1).

<?php
function obscure ($hString, $hDecode = NULL, $hSLength = 10, $keepLength = NULL, $minhPass = 10, $hMethod = sha1)
{
    if (
$hDecode == NULL)
    {
        for (
$i = 0; $i<16; $i++)
        {
           
           
$hSalt = rand(33, 255);
           
$hRandomSalt .= chr($hSalt);
        }
       
$hRandomSalt = hash($hMethod, $hRandomSalt);
    }
    else
    {
       
$hRandomSalt = $hDecode;
    }

    if (
$keepLength != NULL)
    {
       
        if (
$hSLength > (strlen($hRandomSalt) - $minhPass))
        {
           
$hSLength = (strlen($hRandomSalt) - $minhPass);
        }
    }
    else if (
$hSLength < 0)
    {
       
$hSLength = 0;
    }

   
$hLPosition = strlen($hString);

    while (
$hLPosition > $hSLength)
    {
       
$hNumber = substr($hLPosition, -1);
       
       
$hLPosition = $hLPosition * ($hNumber/10);
    }

   
$hLPosition = (integer)$hLPosition;
   
$hRPosition = $hSLength - $hLPosition;

   
$hFSalt = substr($hRandomSalt, 0, $hLPosition);
   
$hLSalt = substr($hRandomSalt, -$hRPosition, $hRPosition);

   
$hPassHash = hash($hMethod, ($hLSalt . $hString . $hFSalt));

    if (
$keepLength != NULL)
    {
        if (
$hSLength != 0)
        {
           
$hPassHash = substr($hPassHash, $hLPosition, -$hRPosition);
        }
    }

    return
$hFSalt . $hPassHash . $hLSalt;
}
?>
up
2
Andre D
9 years ago
Here's a better version of the getDigestNotation() function I posted earlier. (The first version had a bug in the argument checking.)

<?php
function getDigestNotation($rawDigest, $bitsPerCharacter, $chars = NULL)
{
    if (
$chars === NULL || strlen($chars) < 2) {
       
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-,';
    }

    if (
$bitsPerCharacter < 1) {
       
// $bitsPerCharacter must be at least 1
       
$bitsPerCharacter = 1;

    } elseif (
strlen($chars) < pow(2, $bitsPerCharacter)) {
       
// Character length of $chars is too small for $bitsPerCharacter
        // Set $bitsPerCharacter to greatest value allowed by length of $chars
       
$bitsPerCharacter = 1;
       
$minCharLength = 2;

        while (
strlen($chars) >= ($minCharLength *= 2)) {
           
$bitsPerCharacter++;
        }

        unset(
$minCharLength);
    }

   
$bytes = unpack('C*', $rawDigest);
   
$byteCount = count($bytes);

   
$out = '';
   
$byte = array_shift($bytes);
   
$bitsRead = 0;

    for (
$i = 0; $i < $byteCount * 8 / $bitsPerCharacter; $i++) {

        if (
$bitsRead + $bitsPerCharacter > 8) {
           
// Not enough bits remain in this byte for the current character
            // Get remaining bits and get next byte
           
$oldBits = $byte - ($byte >> 8 - $bitsRead << 8 - $bitsRead);

            if (
count($bytes) == 0) {
               
// Last bits; match final character and exit loop
               
$out .= $chars[$oldBits];
                break;
            }

           
$oldBitCount = 8 - $bitsRead;
           
$byte = array_shift($bytes);
           
$bitsRead = 0;

        } else {
           
$oldBitCount = 0;
        }

       
// Read only the needed bits from this byte
       
$bits = $byte >> 8 - ($bitsRead + ($bitsPerCharacter - $oldBitCount));
       
$bits = $bits - ($bits >> $bitsPerCharacter - $oldBitCount << $bitsPerCharacter - $oldBitCount);
       
$bitsRead += $bitsPerCharacter - $oldBitCount;

        if (
$oldBitCount > 0) {
           
// Bits come from seperate bytes, add $oldBits to $bits
           
$bits = ($oldBits << $bitsPerCharacter - $oldBitCount) | $bits;
        }

       
$out .= $chars[$bits];
    }

    return
$out;
}
?>
up
2
Dan
12 years ago
I've noticed websites are now starting to require passwords of a certain length that MUST contain at least 1 non-alphanumeric character. This in itself makes dictionary attacks kind of useless. My web site requires that as well. It uses md5, and appends a site code into the md5 as well. And the include file that contains that site key is outside the public folders. I sure hope I've done enough to keep the bad boys out.
up
2
mark at dot BANSPAM dot pronexus dot nl
13 years ago
Looking for a simple function to implement HMAC-SHA1 but don't want to use the entire PEAR Message lib?

//Calculate HMAC-SHA1 according to RFC2104
// http://www.ietf.org/rfc/rfc2104.txt
function hmacsha1($key,$data) {
    $blocksize=64;
    $hashfunc='sha1';
    if (strlen($key)>$blocksize)
        $key=pack('H*', $hashfunc($key));
    $key=str_pad($key,$blocksize,chr(0x00));
    $ipad=str_repeat(chr(0x36),$blocksize);
    $opad=str_repeat(chr(0x5c),$blocksize);
    $hmac = pack(
                'H*',$hashfunc(
                    ($key^$opad).pack(
                        'H*',$hashfunc(
                            ($key^$ipad).$data
                        )
                    )
                )
            );
    return bin2hex($hmac);
}

It is very useful for client-authentication. see also http://cookies.lcs.mit.edu/pubs/webauth:tr.pdf
Optionally you can change $hashfunc to 'md5' to make this an HMAC-MD5 function ;-)
If you want raw or base64 output instead of hexadecimal, just change the last return line.

Cheers,
Mark

p.s. the "$hmac =" line used to be 1 line but I had to cut it up in order to fit it here ;)
up
2
mgcummings at yahoo dot com
6 years ago
Thought I might save someone else some time trying to figure out how to generate a hash like MySQL5 PASSWORD() makes using just PHP.

$hash = '*' . sha1(sha1($pass), TRUE));
up
2
Helpful Harry
12 years ago
check out these randomized sha1 password storage functions, they output a string of 50 characters, the first 40 characters being a sha1 output based on the last 10 characters - those being a random seed

to encode a password run pw_encode with the password, it'll return a different pseudo-random string every time - store this value.

to check a password run pw_check with the password attempt and the stored value, it'll return true on a match and false otherwise

these functions eliminate the pesky problem of dictionary matches being run on your password lists

<?php

function pw_encode($password)
{
   for (
$i = 1; $i <= 10; $i++)
      
$seed .= substr('0123456789abcdef', rand(0,15), 1);
   return
sha1($seed.$password.$seed).$seed;
}

function
pw_check($password, $stored_value)
{
   if (
strlen($stored_value) != 50)
      return
FALSE;
  
$stored_seed = substr($stored_value,40,10);
   if (
sha1($stored_seed.$password.$stored_seed).$stored_seed == $stored_value)
     return
TRUE;
   else
     return
FALSE;
}

?>
up
2
bobm at hp dot com
14 years ago
To achieve raw binary format prior to PHP5, you can do this...

$raw = pack("H*", sha1($str));

Regards,

Bob Mader
up
1
svn at datapirate dot de
12 years ago
Wanna use SHA-2 algorithm? Try this:

Download Tar-Ball from http://www.adg.us/computers/sha.html
Compile (may occur some warnings) and test it:

cc -O2 -DSHA2_UNROLL_TRANSFORM -Wall -o sha2 sha2prog.c sha2.c
./sha2test.pl

Copy it to /usr/local/bin/ (don't forget to check permissions)

Here are two functions that could be used with:

function sha2($bits, $string){
    $sha2bin="/usr/local/bin/sha2";
    $echocmd="echo";
    if(!in_array($bits, array(256, 384, 512)))return(false);
    $r=exec($echocmd." ".escapeshellarg($string)."|".$sha2bin." -q -".$bits, $sha2);
    return($sha2[0]);
}

function sha2_file($bits, $filename){
    $sha2bin="/usr/local/bin/sha2";
    if(!in_array($bits, array(256, 384, 512)))return(false);
    if(!file_exists($filename)||!is_readable($filename))return(false);
    $r=exec($sha2bin." -q -".$bits." ".escapeshellarg($filename), $sha2);
    return($sha2[0]);
}

and use it like below:

<?php
$str
= 'apple';
if (
sha2(256, $str) === '303980bcb9e9e6cdec515230791af8b0ab1aaa244b58a8d99152673aa22197d0') {
   echo
"Would you like a green or red apple?";
   exit;
}
?>
up
2
Anonymous
8 years ago
Another solution to the salted hash with salt included directly in the hash, while keeping the same length of the result. If you want to generate a hash, call the function without the second argument. If you want to check a password against a hash, use the hash as the second argument. In this case, the function returns the hash itself on success, or boolean false on failure. You can also specify a hash algorithm as the third argument (otherwise SHA-1 will be used).

<?php
function __hash($password, $obscured = NULL, $algorithm = "sha1")
{
 
// whether to use user specified algorithm
 
$mode = in_array($algorithm, hash_algos());
 
// generate random salt
 
$salt = uniqid(mt_rand(), true);
 
// hash it
 
$salt = $mode ? hash($algorithm, $salt) : sha1($salt);
 
// get the length
 
$slen = strlen($salt);
 
// compute the actual length of salt we will use
  // 1/8 to 1/4 of the hash, with shorter passwords producing longer salts
 
$slen = max($slen >> 3, ($slen >> 2) - strlen($password));
 
// if we are checking password against a hash, harvest the actual salt from it, otherwise just cut the salt we already have to the proper size
 
$salt = $obscured ? __harvest($obscured, $slen, $password) : substr($salt, 0, $slen);
 
// hash the password - this is maybe unnecessary
 
$hash = $mode ? hash($algorithm, $password) : sha1($password);
 
// place the salt in it
 
$hash = __scramble($hash, $salt, $password);
 
// and hash it again
 
$hash = $mode ? hash($algorithm, $hash) : sha1($hash);
 
// cut the result so we can add salt and maintain the same length
 
$hash = substr($hash, $slen);
 
// ... do that
 
$hash = __scramble($hash, $salt, $password);
 
// and return the result
 
return $obscured && $obscured !== $hash ? false : $hash;
}
?>

It uses a random, variable length salt, depending on the length of the password. The functions __scramble() and __harvest() are used to place salt into the hash or pull it out respectively. You can write your own, and of course the strength of the result greatly depends on them. They can be relatively simple yet still quite secure:

<?php
function __scramble($hash, $salt, $password)
{
  return
substr($hash, 0, strlen($password)) . $salt . substr($hash, strlen($password));
}

function
__harvest($obscured, $slen, $password)
{
  return
substr($obscured, min(strlen($password), strlen($obscured) - $slen), $slen);
}
?>

Or they can be ridiculously complicated (my favourite kind):

<?php
function __scramble($hash, $salt, $password)
{
 
$k = strlen($password); $j = $k = $k > 0 ? $k : 1; $p = 0; $index = array(); $out = ""; $m = 0;
  for (
$i = 0; $i < strlen($salt); $i++)
  {
   
$c = substr($password, $p, 1);
   
$j = pow($j + ($c !== false ? ord($c) : 0), 2) % (strlen($hash) + strlen($salt));
    while (
array_key_exists($j, $index))
     
$j = ++$j % (strlen($hash) + strlen($salt));
   
$index[$j] = $i;
   
$p = ++$p % $k;
  }
  for (
$i = 0; $i < strlen($hash) + strlen($salt); $i++)
   
$out .= array_key_exists($i, $index) ? $salt[$index[$i]] : $hash[$m++];
  return
$out;
}

function
__harvest($obscured, $slen, $password)
{
 
$k = strlen($password); $j = $k = $k > 0 ? $k : 1; $p = 0; $index = array(); $out = "";
  for (
$i = 0; $i < $slen; $i++)
  {
   
$c = substr($password, $p, 1);
   
$j = pow($j + ($c !== false ? ord($c) : 0), 2) % strlen($obscured);
    while (
in_array($j, $index))
     
$j = ++$j % strlen($obscured);
   
$index[$i] = $j;
   
$p = ++$p % $k;
  }
  for (
$i = 0; $i < $slen; $i++)
   
$out .= $obscured[$index[$i]];
  return
$out;
}
?>
up
1
erling dot westenvik at gmail dot com
11 years ago
Regarding php at REMOVEMEkennel17 dot co dot uk's note below:

The phrase: "To get the correct behaviour", would perhaps be better off if it read: "To get the wanted (but not recommended) behaviour".

Always honor the expected data types for functions: sha1 expects a string as input, and returns a string on exit. NULL, TRUE and FALSE are not string data types. The string "" is a string as good as "any". By following the "logic" that sha1("") should return "", then what should sha1("a") return? "b"? "c"?

An authentication system that allows for blank passwords is not really an authentication system in the first place. What you are describing is merely a way to tell the application that you want to see data in some specific context, like sorted by user name, etc. Create other tools for this purpose and leave the authentication system to deal with what it is supposed to do: Granting users access to restricted data and blocking other users from seeing the same data.

Don't store passwords in clear text, but salt and encrypt them. That way it makes perfect sense having <?php $sStoredPwd === sha1($sStoredSalt . $_POST["sTypedPwd"]); ?>, even with a blank "password". No other person than the user itself, not even the programmer, should know the password or be able to guess it. If the user forgets the password, a new one must be generated.

Regards,
Erling
up
-1
jcastromail at yahoo dot es
1 year ago
Hi there:

About the complexity of sha1, sha1 generates a code a different code each 1,4615016373309029182036848327163e+48 (2 ^ 160 bits).  So the chances of the use of the same hash is really small.

The "problem" of sha1 (and md5) is the speed of the generation. However, the speed is proportional with the length of the text to encrypt.

However, using a SALT, it increases tenfold times the security, even for a weak password.

In gross terms, a password of 6 characters can be hacked in a minute (if its store in md5 or sha).   However, a password of 7 characters takes an hour, a password of 8 a year and a password of more than 8 character is virtually inviable of hack.

However, if we used an SALT (a secret salt btw), then even a password of 3 characters will be really safe.

sha1('SALT SECRET TEXT!!@@@aaa0000'.'123');

And a double sha1 will ensure more safety

sha1(sha1('SALT SECRET TEXT'.'123',false),false)

It will require a rainbow table of 20 characters, enough big to be absurdly safe even for a thousand of servers running during a year.
up
0
php at wbhostmax dot de
5 years ago
<?php
function DoubleSaltedHash($pw, $salt) {
    return
sha1($salt.