|
|
 |
sha1 (PHP 4 >= 4.3.0, PHP 5) sha1 -- Calculate the sha1 hash of a string Descriptionstring sha1 ( string str [, bool raw_output] )
Calculates the sha1 hash of str using the
US Secure Hash Algorithm 1,
and returns that hash. The hash is a 40-character hexadecimal number.
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.
Note:
The optional raw_output parameter was added in
PHP 5.0.0 and defaults to FALSE
Example 1. A sha1() example |
<?php
$str = 'apple';
if (sha1($str) === 'd0be2dc421be4fcd0172e5afceea3970e2f3d940') {
echo "Would you like a green or red apple?";
exit;
}
?>
|
|
See also sha1_file(),
crc32(), and
md5()
User Contributed Notes
sha1
alex at milivojevic dot org
28-Apr-2005 04:12
Regarding my previous comment, if you want to be on the safe side and use only ASCII printable seeds (shouldn't matter for SSHA seeds), something like this could be used:
<?php
$salt = substr(base64_encode(pack("H*", sha1(mt_rand()))), 0, 4);
?>
alex at milivojevic dot org
28-Apr-2005 12:45
If you don't have mhash library and/or PHP module (for example, Red Hat systems, which includes Fedora), and you don't feel like adding it, you can use something like this to generate and verify SSHA hashes.
<?php
$password = "test";
mt_srand((double)microtime()*1000000);
$salt = pack("CCCC", mt_rand(), mt_rand(), mt_rand(), mt_rand());
$hash = "{SSHA}" . base64_encode(pack("H*", sha1($password . $salt)) . $salt);
echo $hash . "\n";
$ohash = base64_decode(substr($hash, 6));
$osalt = substr($ohash, 20);
$ohash = substr($ohash, 0, 20);
$nhash = pack("H*", sha1($password . $osalt));
if ($ohash == $nhash) {
echo "Password OK\n";
} else {
echo "Password verifiaction failed\n";
}
?>
Keamos at gmail dot com
05-Mar-2005 04:19
Or, you could use cryptopp-php (a PHP version of crypto++), which you can get at http://bugs.tutorbuddy.com/versions.php/cryptopp-php
It supports (for hashing):
MD2
MD4
MD5
RIPEMD-128
RIPEMD-160
RIPEMD-256
RIPEMD-320
SHA1
SHA-256
SHA-384
SHA-512
Tiger
Whirlpool
(SHA256/384/512, Tiger and Whirlpool only on systems using word64)
svn at datapirate dot de
20-Feb-2005 07:26
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;
}
?>
dayoman at webfreax dot nl
17-Feb-2005 05:04
mina86 at tlen dot pl
09-Jan-2005 10:17
I did my own implementation of SHA-1 algorithm, which is faster (more then 10 times according to my benchamrk) then both, SHA1Lib and sinatosk's implementation. My library uses mhash if available as described by labarks. You can get it from CVS: http://cvs.sourceforge.net/viewcvs.py/yggdrasil-cms/ -> yggdrasil/include/sha1.inc.php (no direct link due to site's limitations) note, however, that the web interface to view the CVS files has some delay.
hans at pennywaffer dot net
19-Dec-2004 10:18
You can also use sha1() to create a fixed sized ID based on the folderpath containing the performing script. Imagine an environment where multiple instances of a script are running simultaneously, making use of session variables (a good example would be thumbnaildirectories that each contain an instance of a thumbnailmanager). To prevent your $_SESSION array from getting influenced by other scripts that are on the same server and run from the same browserwindow (and thus having the same session ID), use the following approach:
session_start();
$myDir = sha1(dirname(__FILE__));
$_SESSION[$myDir]['var'] = etc;
instead of just using $_SESSION['var'] = etc;
This way your userauthentication and shoppingcart data won't get mixed up. The use of sha1() also prevents strange symbols or spaces in the folderpath messing up the ID, and makes sure the ID has a constant size regardless the length of the path.
sinatosk at gmail dot com
22-Nov-2004 02:43
Heres an SHA1 function that will work on it's own completely. This is for users who are using below PHP 4.3.0. it works same as PHP5 ( being able to return raw output ).
<?php
function sha1_str2blks_SHA1($str)
{
$strlen_str = strlen($str);
$nblk = (($strlen_str + 8) >> 6) + 1;
for ($i=0; $i < $nblk * 16; $i++) $blks[$i] = 0;
for ($i=0; $i < $strlen_str; $i++)
{
$blks[$i >> 2] |= ord(substr($str, $i, 1)) << (24 - ($i % 4) * 8);
}
$blks[$i >> 2] |= 0x80 << (24 - ($i % 4) * 8);
$blks[$nblk * 16 - 1] = $strlen_str * 8;
return $blks;
}
function sha1_safe_add($x, $y)
{
$lsw = ($x & 0xFFFF) + ($y & 0xFFFF);
$msw = ($x >> 16) + ($y >> 16) + ($lsw >> 16);
return ($msw << 16) | ($lsw & 0xFFFF);
}
function sha1_rol($num, $cnt)
{
return ($num << $cnt) | sha1_zeroFill($num, 32 - $cnt);
}
function sha1_zeroFill($a, $b)
{
$bin = decbin($a);
$strlen_bin = strlen($bin);
$bin = $strlen_bin < $b ? 0 : substr($bin, 0, $strlen_bin - $b);
for ($i=0; $i < $b; $i++) $bin = '0'.$bin;
return bindec($bin);
}
function sha1_ft($t, $b, $c, $d)
{
if ($t < 20) return ($b & $c) | ((~$b) & $d);
if ($t < 40) return $b ^ $c ^ $d;
if ($t < 60) return ($b & $c) | ($b & $d) | ($c & $d);
return $b ^ $c ^ $d;
}
function sha1_kt($t)
{
if ($t < 20) return 1518500249;
if ($t < 40) return 1859775393;
if ($t < 60) return -1894007588;
return -899497514;
}
function sha1($str, $raw_output=FALSE)
{
if ( $raw_output === TRUE ) return pack('H*', sha1($str, FALSE));
$x = sha1_str2blks_SHA1($str);
$a = 1732584193;
$b = -271733879;
$c = -1732584194;
$d = 271733878;
$e = -1009589776;
$x_count = count($x);
for ($i = 0; $i < $x_count; $i += 16)
{
$olda = $a;
$oldb = $b;
$oldc = $c;
$oldd = $d;
$olde = $e;
for ($j = 0; $j < 80; $j++)
{
$w[$j] = ($j < 16) ? $x[$i + $j] : sha1_rol($w[$j - 3] ^ $w[$j - 8] ^ $w[$j - 14] ^ $w[$j - 16], 1);
$t = sha1_safe_add(sha1_safe_add(sha1_rol($a, 5), sha1_ft($j, $b, $c, $d)), sha1_safe_add(sha1_safe_add($e, $w[$j]), sha1_kt($j)));
$e = $d;
$d = $c;
$c = sha1_rol($b, 30);
$b = $a;
$a = $t;
}
$a = sha1_safe_add($a, $olda);
$b = sha1_safe_add($b, $oldb);
$c = sha1_safe_add($c, $oldc);
$d = sha1_safe_add($d, $oldd);
$e = sha1_safe_add($e, $olde);
}
return sprintf('%08x%08x%08x%08x%08x', $a, $b, $c, $d, $e);
}
?>
rsemirag at yahoo dot com
02-Nov-2004 12:34
If you're struggling to generate an SHA encoded password for LDAP (PHP < 5.0), what you end up needing is this:
$userpassword = base64_encode(pack("H*", sha1($pass)));
I found this in the OpenLDAP FAQ (many thanks to Google and Ace), though I'm using the iPlanet LDAP server.
Ray Semiraglio
brian_bisaillon at rogers dot com
25-Feb-2004 10:19
Source code to create SSHA passwords...
public function HashPassword($password)
{
mt_srand((double)microtime()*1000000);
$salt = mhash_keygen_s2k(MHASH_SHA1, $password, substr(pack('h*', md5(mt_rand())), 0, 8), 4);
$hash = "{SSHA}".base64_encode(mhash(MHASH_SHA1, $password.$salt).$salt);
return $hash;
}
Source code to validate SSHA passwords...
public function ValidatePassword($password, $hash)
{
$hash = base64_decode(substr($hash, 6));
$original_hash = substr($hash, 0, 20);
$salt = substr($hash, 20);
$new_hash = mhash(MHASH_SHA1, $password . $salt);
if (strcmp($original_hash, $new_hash) == 0)
... do something because your password is valid ...
else
echo 'Unauthorized: Authorization has been refused for the credentials you provided. Please login with a valid username and password.';
... be sure to clear your session data ...
}
Note: The format is compatible with OpenLDAP's SSHA scheme if I'm not mistaken.
mark at dot BANSPAM dot pronexus dot nl
30-Jan-2004 08:28
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 ;)
labarks
15-Nov-2003 05:06
Append this to the your sha1lib file to make it more portable. If your version of php does support sha1() then it will try to use Mhash or else it will use the sha1lib. Use $sha1 if you want to display which is being used.
if ( function_exists('sha1') )
$sha1 = "sha1";
if ( !function_exists('sha1') && function_exists('mhash'))
{
function sha1($hash_source)
{
$hash = mhash(MHASH_SHA1, $hash_source);
$hex_hash = bin2hex($hash);
return $hex_hash;
}
$sha1 = "Mhash";
}
if ( !function_exists('sha1') && !function_exists('mhash'))
{
function sha1( $string, $raw_output = false )
{
$library = new Sha1Lib();
return $raw_output ? $library->str_sha1($string) : $library->hex_sha1($string);
}
$sha1 = "sha1lib";
}
andreas at schmeiler dot de
16-Oct-2003 01:50
To use the sha1 function in php versions <4.3 do the following:
install the mhash library (see http://mhash.sourceforge.net)
then, sha1 can be implemented as follows:
function sha1($hash_source) {
$hash = mhash(MHASH_SHA1, $hash_source);
$hex_hash = bin2hex($hash);
return $hex_hash;
}
bobm at hp dot com
23-Apr-2003 11:12
To achieve raw binary format prior to PHP5, you can do this...
$raw = pack("H*", sha1($str));
Regards,
Bob Mader
| |