如何使用php / shell计算sha-512的影子密码

时间:2011-10-29 18:20:14

标签: php linux passwords

我使用密码delme创建了帐户sysadmin。然后我想用php计算密码的sha-512。

我预计这会产生相同的哈希...

billy@iserve:~$ sudo cat /etc/shadow | grep sysadmin
sysadmin:$6$q5HxMEDr$VUPS0JrRFv5bohFtsscvjQ7t2fUhi0m2z8f0ObKtorwlSHqiGde8N9hprkqmnB9LOtEDorG.3yBSXYSAKcJmz.:15276:0:99999:7:::
billy@iserve:~$ php -r "echo crypt('delme','$6$rounds=5000$q5HxMEDr$').\"\n"\";"
=54Jjswxnfslg

我无法在影子文件中复制密码......你能告诉我怎么做吗?

4 个答案:

答案 0 :(得分:1)

这是因为真实系统使用的是随机生成的盐(在第二个$和第三个$之间)。你在PHP代码中使用相同的盐吗?

答案 1 :(得分:1)

我最终这样做是为了解决我的问题...

/*    Need to add www-data to group shadow (and restart apache)
        $ sudo adduser www-data shadow
        $ sudo /etc/init.d/apache2 restart
      Needs whois to be installed to run mkpasswd
        $ sudo apt-get install whois
      Assumes that sha-512 is used in shadow file
*/

function authenticate($user, $pass){
  // run shell command to output shadow file, and extract line for $user
  // then split the shadow line by $ or : to get component parts
  // store in $shad as array
  $shad =  preg_split("/[$:]/",`cat /etc/shadow | grep "^$user\:"`);
  // use mkpasswd command to generate shadow line passing $pass and $shad[3] (salt)
  // split the result into component parts and store in array $mkps
  $mkps = preg_split("/[$:]/",trim(`mkpasswd -m sha-512 $pass $shad[3]`));
  // compare the shadow file hashed password with generated hashed password and return
  return ($shad[4] == $mkps[3]);
}

// usage...
if(authenticate('myUsername','myPassword')){
  // logged in   
} else {
  // not valid user
}

我对这种方法的安全性并不完全有信心,所以会问这个问题。

答案 2 :(得分:0)

PHP代码中只有一个错误。您必须转义$符号!

$ echo "<?php \$foo=crypt('delme', '\$6\$q5HxMEDr\$'); echo \$foo; ?>" | php5-cgi; echo ""
X-Powered-By: PHP/5.4.4-14+deb7u7
Content-type: text/html

$6$q5HxMEDr$VUPS0JrRFv5bohFtsscvJQ7tZfUhi0m2z8f0ObKtorwlSHqiGde8N9hprkqmnB9LOtEDorG.3yBSXYSAKcJmz.

答案 3 :(得分:-1)

对比利的回答几乎没有更新:

function authenticate($user, $pass){
  $shad =  preg_split("/[$:]/",`cat /etc/shadow | grep "^$user\:"`);
  if (!isset($shad[2]) || !isset($shad[3])) return false;
  $mkps = preg_split("/[$:]/",crypt($pass, '$'.$shad[2].'$'.$shad[3].'$'));
  return ($shad[4] == $mkps[3]);
}