Guest User

bcrypt

a guest
Aug 31st, 2013
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.52 KB | None | 0 0
  1. class Bcrypt
  2. {
  3. private $rounds;
  4. public function __construct($rounds = 12) {
  5. if(CRYPT_BLOWFISH != 1) {
  6. throw new Exception("bcrypt not supported in this installation. See http://php.net/crypt");
  7. }
  8.  
  9. $this->rounds = $rounds;
  10. }
  11.  
  12. public function hash($input) {
  13. $hash = crypt($input, $this->getSalt());
  14.  
  15. if(strlen($hash) > 13)
  16. return $hash;
  17.  
  18. return false;
  19. }
  20.  
  21. public function verify($input, $existingHash) {
  22. $hash = crypt($input, $existingHash);
  23.  
  24. return $hash === $existingHash;
  25. }
  26.  
  27. private function getSalt() {
  28. $salt = sprintf('$2a$%02d$', $this->rounds);
  29.  
  30. $bytes = $this->getRandomBytes(16);
  31.  
  32. $salt .= $this->encodeBytes($bytes);
  33.  
  34. return $salt;
  35. }
  36.  
  37. private $randomState;
  38. private function getRandomBytes($count) {
  39. $bytes = '';
  40.  
  41. if(function_exists('openssl_random_pseudo_bytes') &&
  42. (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')) { // OpenSSL slow on Win
  43. $bytes = openssl_random_pseudo_bytes($count);
  44. }
  45.  
  46. if($bytes === '' && is_readable('/dev/urandom') &&
  47. ($hRand = @fopen('/dev/urandom', 'rb')) !== FALSE) {
  48. $bytes = fread($hRand, $count);
  49. fclose($hRand);
  50. }
  51.  
  52. if(strlen($bytes) < $count) {
  53. $bytes = '';
  54.  
  55. if($this->randomState === null) {
  56. $this->randomState = microtime();
  57. if(function_exists('getmypid')) {
  58. $this->randomState .= getmypid();
  59. }
  60. }
  61.  
  62. for($i = 0; $i < $count; $i += 16) {
  63. $this->randomState = md5(microtime() . $this->randomState);
  64.  
  65. if (PHP_VERSION >= '5') {
  66. $bytes .= md5($this->randomState, true);
  67. } else {
  68. $bytes .= pack('H*', md5($this->randomState));
  69. }
  70. }
  71.  
  72. $bytes = substr($bytes, 0, $count);
  73. }
  74.  
  75. return $bytes;
  76. }
  77.  
  78. private function encodeBytes($input) {
  79. // The following is code from the PHP Password Hashing Framework
  80. $itoa64 = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  81.  
  82. $output = '';
  83. $i = 0;
  84. do {
  85. $c1 = ord($input[$i++]);
  86. $output .= $itoa64[$c1 >> 2];
  87. $c1 = ($c1 & 0x03) << 4;
  88. if ($i >= 16) {
  89. $output .= $itoa64[$c1];
  90. break;
  91. }
  92.  
  93. $c2 = ord($input[$i++]);
  94. $c1 |= $c2 >> 4;
  95. $output .= $itoa64[$c1];
  96. $c1 = ($c2 & 0x0f) << 2;
  97.  
  98. $c2 = ord($input[$i++]);
  99. $c1 |= $c2 >> 6;
  100. $output .= $itoa64[$c1];
  101. $output .= $itoa64[$c2 & 0x3f];
  102. } while (1);
  103.  
  104. return $output;
  105. }
  106. }
Advertisement
Add Comment
Please, Sign In to add comment