3 use Wikimedia\Assert\Assert
;
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
25 * Implements Argon2, a modern key derivation algorithm designed to resist GPU cracking and
26 * side-channel attacks.
28 * @see https://en.wikipedia.org/wiki/Argon2
30 class Argon2Password
extends Password
{
32 * @var null[] Array with known password_hash() option names as keys
34 private static $knownOptions = [
35 'memory_cost' => null,
43 protected function isSupported() {
44 // It is actually possible to have a PHP build with Argon2i but not Argon2id
45 return defined( 'PASSWORD_ARGON2I' ) ||
defined( 'PASSWORD_ARGON2ID' );
49 * @return mixed[] Array of 2nd and third parmeters to password_hash()
51 private function prepareParams() {
52 switch ( $this->config
['algo'] ) {
54 $algo = PASSWORD_ARGON2I
;
57 $algo = PASSWORD_ARGON2ID
;
60 $algo = defined( 'PASSWORD_ARGON2ID' ) ? PASSWORD_ARGON2ID
: PASSWORD_ARGON2I
;
63 throw new LogicException( "Unexpected algo: {$this->config['algo']}" );
67 $params = array_intersect_key( $this->config
, self
::$knownOptions );
69 return [ $algo, $params ];
75 public function crypt( $password ) {
76 list( $algo, $params ) = $this->prepareParams();
77 $this->hash
= password_hash( $password, $algo, $params );
83 public function equals( $other ) {
84 if ( is_string( $other ) ) {
85 return $this->verify( $other );
88 // Argon2 key derivation is not deterministic, can't pass objects to equals()
95 public function verify( $password ) {
96 Assert
::parameterType( 'string', $password, '$password' );
98 return password_verify( $password, $this->hash
);
104 public function toString() {
105 $res = ":argon2:{$this->hash}";
106 $this->assertIsSafeSize( $res );
113 public function needsUpdate() {
114 list( $algo, $params ) = $this->prepareParams();
115 return password_needs_rehash( $this->hash
, $algo, $params );