add some changes
[Snippets.git] / bcrypt.class.php
CommitLineData
934f0434
S
1<?php
2/**
3 * @author Jan Altensen (Stricted)
4 * @copyright 2013-2014 Jan Altensen (Stricted)
5 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
6 */
7class bcrypt {
8 /**
9 * compare password with given hash
10 *
11 * @param string $password
12 * @param string $hash
13 * @return boolean
14 */
15 public function compare ($password, $hash) {
16 $salt = $this->getSalt($hash);
17
18 $new = crypt($password, $salt);
19 $doubleSalted = crypt(crypt($password, $salt), $salt);
20
21 if ($new == $hash) {
22 return true;
23 }
24 else if ($doubleSalted == $hash) {
25 return true;
26 }
27
28 return false;
29 }
30
31 /**
32 * crypt new password
33 *
34 * @param string $password
701c06d4 35 * @param string $double
934f0434
S
36 * @return string
37 */
38 public function crypt ($password, $double = false) {
39 $salt = $this->generateSalt();
40 if ($double) {
41 return crypt(crypt($password, $salt), $salt);
42 }
43 else {
44 return crypt($password, $salt);
45 }
46 }
47
48 /**
49 * generate new salt
50 *
51 * @return string
52 */
53 public function generateSalt() {
54 $blowfishCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789./';
55 $maxIndex = strlen($blowfishCharacters) - 1;
56 $salt = '';
57
58 for ($i = 0; $i < 22; $i++) {
59 $rand = mt_rand(0, $maxIndex);
60 $salt .= $blowfishCharacters[$rand];
61 }
62
63 return '$2a$08$' . $salt;
64 }
65
66 /**
67 * get salt from password hash
68 *
69 * @param string $hash
70 * @return string
71 */
72 private function getSalt($hash) {
73 $salt = '';
74 if (mb_substr($hash, 0, 7) == '$2a$08$') {
75 $salt = mb_substr($hash, 7, 22);
76 }
77 else {
78 $salt = mb_substr($hash, 0, 22);
79 }
80
81 return '$2a$08$' . $salt;
82 }
83}
84?>