#!/usr/bin/php
<?php
/**
 * Script to verify WordPress password
 * Usage: php wp_password_check.php <password> <hash>
 * Exit code: 0 if password is correct, 1 if not
 */

if ($argc !== 3) {
    echo "Usage: php wp_password_check.php <password> <hash>\n";
    exit(1);
}

$password = $argv[1];
$hash = $argv[2];

function wp_check_password($password, $hash) {
    // From Wordpress 6.8 code
    if ( strlen( $hash ) <= 32 ) {
        // Check the hash using md5 regardless of the current hashing mechanism.
        $check = hash_equals( $hash, md5( $password ) );
    } elseif ( ! empty( $wp_hasher ) ) {
        // Check the password using the overridden hasher.
        $check = $wp_hasher->CheckPassword( $password, $hash );
    } elseif ( strlen( $password ) > 4096 ) {
        // Passwords longer than 4096 characters are not supported.
        $check = false;
    } elseif ( str_starts_with( $hash, '$wp' ) ) {
        // Check the password using the current prefixed hash.
        $password_to_verify = base64_encode( hash_hmac( 'sha384', $password, 'wp-sha384', true ) );
        $check = password_verify( $password_to_verify, substr( $hash, 3 ) );
    } elseif ( str_starts_with( $hash, '$P$' ) ) {
        // Check the password using phpass.
        // NOTE: not supported
        //require_once ABSPATH . WPINC . '/class-phpass.php';
        //$check = ( new PasswordHash( 8, true ) )->CheckPassword( $password, $hash );
    } else {
        // Check the password using compat support for any non-prefixed hash.
        $check = password_verify( $password, $hash );
    }
    return $check;
}

// Verify the password against the hash
if (wp_check_password($password, $hash)) {
    exit(0);
} else {
    exit(1);
}
?>
