security.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. function salt(){
  3. return uniqid(mt_rand(0,61), true);
  4. }
  5. function saltedHash($pass,$salt){
  6. $hash = $pass.$salt;
  7. for($i = 0;$i<50;$i++){
  8. $hash = hash('sha512',$pass.$hash.$salt);
  9. }
  10. return $hash;
  11. }
  12. function compareSaltedHash($pass,$salt,$hash){
  13. return $hash == saltedHash($pass,$salt);
  14. }
  15. function securityKey($username,$salt){
  16. return saltedHash($username,$salt);
  17. }
  18. function authenticate(){
  19. if(loggedIn()){
  20. setKey(getKey());
  21. }
  22. }
  23. function login($username,$password){
  24. global $LOGGEDIN;
  25. if($res = query("SELECT name,password,salt FROM `users` WHERE name = '%s'",Array($username))){
  26. if($res->num_rows == 1){
  27. $row = $res->fetch_assoc();
  28. if(compareSaltedHash($password,$row['salt'],$row['password'])){
  29. $_SESSION['username'] = $username;
  30. $key = securityKey($username,$_SERVER['REMOTE_ADDR']);
  31. setKey($key);
  32. $LOGGEDIN = true;
  33. return $key;
  34. }
  35. }
  36. }
  37. return false;
  38. }
  39. function loggedIn(){
  40. global $LOGGEDIN;
  41. global $_COOKIE;
  42. if(isset($_COOKIE['username'])&&isset($_COOKIE['key'])){
  43. if(securityKey($_COOKIE['username'],$_SERVER['REMOTE_ADDR'])==$_COOKIE['key']){
  44. $_SESSION['username'] = $_COOKIE['username'];
  45. setKey($_COOKIE['key']);
  46. $LOGGEDIN = true;
  47. return true;
  48. }
  49. }
  50. setKey(null);
  51. $LOGGEDIN = false;
  52. return false;
  53. }
  54. function setKey($key){
  55. if($key == null){
  56. unset($_SESSION['key']);
  57. unset($_SESSION['username']);
  58. }else{
  59. $_SESSION['key'] = $key;
  60. setcookie('username',$_SESSION['username'],time()+get('timeout'));
  61. setcookie('key',$key,time()+get('timeout'));
  62. }
  63. return $key;
  64. }
  65. function getKey(){
  66. return isset($_SESSION['key'])?$_SESSION['key']:null;
  67. }
  68. ?>