I want to test (unit testing) HashPassword($password)
method from WordPress.
How I can check that HashPassword("123123") will return the correct hash for it?
For example, I want to do something like:
$hashFor123123 = "$P$P)230230832482349823";
$result = HashPassword("123123");
$this->assertSame($hashFor123123, $result);
But, HashPassword method each time returns a new string with hash. That is why I cant do assert.
How to test it?
CodePudding user response:
Password hashing uses a random salt, so each time you hash the same password you'll get a different value back. The theory is explained here, even though WordPress doesn't use the php password hashing functions, but rather their own. You cannot compare hashes; you can only check whether a given unhashed password matches a hash.
The random salt defeats cybercreeps' use of rainbow lookup tables to recover passwords given their hashes. This helps keep your users' passwords secret even if a cybercreep manages to steal your wp_users table. Defense in depth, it's called.
In WordPress, you can hash a password and then check it using wp_hash_password() and wp_check_password(), something like this.
$hash = wp_hash_password( '123123' );
if ( wp_check_password( '123123', $hash )) {
/* it worked */
} else {
/* it did not work */
}
It's not clear why it is worth your time to unit-test this subsystem. It is used in production many billions of times every day around the world.
CodePudding user response:
The reason that the result is different every time you call HashPassword
is because your password is prefixed by a random salt before it's hashed.
To compare a plaintext password against a known hash, you have to call CheckPassword
.