diff --git a/Tests/passwordTest.php b/Tests/passwordTest.php new file mode 100644 index 0000000..b0f9264 --- /dev/null +++ b/Tests/passwordTest.php @@ -0,0 +1,49 @@ +assertSame (substr ($res, 0, 4), "$2y$"); + } + + public function test_cryptPasswd_2 () + { + // Test the randomization of the salt : must be different each time + $res1 = \password::cryptPasswd ("AAA"); + echo "RES1=$res1\n"; + $res2 = \password::cryptPasswd ("AAA"); + echo "RES2=$res2\n"; + $res3 = \password::cryptPasswd ("AAA"); + echo "RES3=$res3\n"; + $this->assertSame (count (array_unique (array ($res1, $res2, $res3))), 3); + // Three passwords : each must have a different result + } + + public function test_checkPassword_1 () + { + $res = \password::checkPassword ("AAA", "AAA"); + $this->assertSame ($res, false); + } + + public function test_checkPassword_2 () + { + $res = \password::checkPassword ("AAA", \password::cryptPasswd ("AAA")); + $this->assertSame ($res, true); + } + + public function test_checkPassword_3 () + { + $res = \password::checkPassword ("AAA", \password::cryptPasswd ("BBB")); + $this->assertSame ($res, false); + } + + public function test_checkPassword_4 () + { + $res = \password::checkPassword ("AAA", + '$2y$11$Y.E98jbjgDpV61eK..9MT.klzTeg7ulO4WH/B5yA8cAGMIh.zoNXq'); + $this->assertSame ($res, true); + } +} diff --git a/password.php b/password.php new file mode 100644 index 0000000..129d753 --- /dev/null +++ b/password.php @@ -0,0 +1,48 @@ +=PHP 5.3.7) + str_pad ($cost, 2, "0", STR_PAD_LEFT), //add the cost in two digits + $salt //add the salt + )); + //now do the actual hashing + return crypt ($password, $param); + } + + /** Check if the clear password is valid against the hashed one + * @param string $clear The clear password + * @param string $hashed The hashed password + * @return boolean true if the password correspond to the hash + */ + static public function checkPassword ($clear, $hashed) + { + if (! is_string ($clear)) + throw new \Exception (dgettext ("domframework", + "Invalid clear password provided to be checked : not a string"), 403); + if (! is_string ($clear)) + throw new \Exception (dgettext ("domframework", + "Invalid hashed password provided to be checked : not a string"), 403); + if (crypt ($clear, $hashed) === $hashed) + return true; + return false; + } +}