There are so many hash. SHA1 is one of them which is widely used in recent years even though it is not safe to use right now. By the way, it is still the default hash function for storing password in LDAP especially OpenLDAP. In order to develop a website with LDAP authentication manually against POSIX account, SSHA hash function or SHA1 is the easiest solution.

Below are 2 functions for encoding given text to SSHA including {SSHA} and another one for verifying given text against SSHA hash.

function ssha_encode($text) {
  for ($i=1;$i<=10;$i++) {
    $salt .= substr('0123456789abcdef',rand(0,15),1);
  }
  $hash = "{SSHA}".base64_encode(pack("H*",sha1($text.$salt)).$salt);
  return $hash;
}
 
function ssha_check($text,$hash) {
  $ohash = base64_decode(substr($hash,6));
  $osalt = substr($ohash,20);
  $ohash = substr($ohash,0,20);
  $nhash = pack("H*",sha1($text.$osalt));
  return $ohash == $nhash;
}

For example, I would like to encode a password "test". One possible encrypted hash is
 {SSHA}5s6PB5P6KET18sZLycLKKNBFf71jMzkzNzk4Yzg2.

$password = "test";
$hash = ssha_encode($password);
print "$hash\n";
print var_export(ssha_check($password,$hash),true);

鱼漂注:
从SSHA的生成代码不难看出,SSHA用了一些随机生成的加密种子,这里只用了1位,通常也可以使用多位随机生成的加密种子.

Program | 评论(0) | 引用(0) | 阅读(5583)