Guest User

Untitled

a guest
May 26th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. #!/usr/bin/php
  2. <?PHP
  3. // Generates a strong password of N length containing at least one lower case letter,
  4. // one uppercase letter, one digit, and one special character. The remaining characters
  5. // in the password are chosen at random from those four sets.
  6. //
  7. // The available characters in each set are user friendly - there are no ambiguous
  8. // characters such as i, l, 1, o, 0, etc. This, coupled with the $add_dashes option,
  9. // makes it much easier for users to manually type or speak their passwords.
  10. //
  11. // Note: the $add_dashes option will increase the length of the password by
  12. // floor(sqrt(N)) characters.
  13.  
  14. function generateStrongPassword($length = 15, $add_dashes = false, $available_sets = 'luds')
  15. {
  16. $sets = array();
  17. if(strpos($available_sets, 'l') !== false)
  18. $sets[] = 'abcdefghjkmnpqrstuvwxyz';
  19. if(strpos($available_sets, 'u') !== false)
  20. $sets[] = 'ABCDEFGHJKMNPQRSTUVWXYZ';
  21. if(strpos($available_sets, 'd') !== false)
  22. $sets[] = '23456789';
  23. if(strpos($available_sets, 's') !== false)
  24. $sets[] = '!@#$%&*?';
  25.  
  26. $all = '';
  27. $password = '';
  28. foreach($sets as $set)
  29. {
  30. $password .= $set[tweak_array_rand(str_split($set))];
  31. $all .= $set;
  32. }
  33.  
  34. $all = str_split($all);
  35. for($i = 0; $i < $length - count($sets); $i++)
  36. $password .= $all[tweak_array_rand($all)];
  37.  
  38. $password = str_shuffle($password);
  39.  
  40. if(!$add_dashes)
  41. return $password;
  42.  
  43. $dash_len = floor(sqrt($length));
  44. $dash_str = '';
  45. while(strlen($password) > $dash_len)
  46. {
  47. $dash_str .= substr($password, 0, $dash_len) . '-';
  48. $password = substr($password, $dash_len);
  49. }
  50. $dash_str .= $password;
  51. return $dash_str;
  52. }
  53. //take a array and get random index, same function of array_rand, only diference is
  54. // intent use secure random algoritn on fail use mersene twistter, and on fail use defaul array_rand
  55. function tweak_array_rand($array){
  56. if (function_exists('random_int')) {
  57. return random_int(0, count($array) - 1);
  58. } elseif(function_exists('mt_rand')) {
  59. return mt_rand(0, count($array) - 1);
  60. } else {
  61. return array_rand($array);
  62. }
  63. }
  64. echo generateStrongPassword();
  65. echo "\n";
Add Comment
Please, Sign In to add comment