Skip to content

Instantly share code, notes, and snippets.

@kenarsuleyman
Last active March 13, 2023 06:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kenarsuleyman/8f24061a489dbbc878fcbc64f60fd4a7 to your computer and use it in GitHub Desktop.
Save kenarsuleyman/8f24061a489dbbc878fcbc64f60fd4a7 to your computer and use it in GitHub Desktop.
Migrate Magento2 Argon hashed passwords to WordPress
// Run migration on login process
add_filter( 'check_password', 'migrate_magento_password', 10, 4 );
function migrate_magento_password( $check, $password, $hash, $user_id ) {
if ( $check ) {
// password is valid, no need to migrate
return $check;
}
// get Magento password data
$mage_pwd_data = get_user_meta( $user_id, 'mage_pwd_data', true );
if ( ! $mage_pwd_data ) {
// exit early if we were unable to retrieve a Magento hashed password
// means user typed a wrong WordPress password
return $check;
}
$magento_pwd_parts = explode(':', $mage_pwd_data);
if ( ! is_array( $magento_pwd_parts ) ) {
// Magento password data is not in the expected format
return $check;
}
$hash = $magento_pwd_parts['0'];
$salt = $magento_pwd_parts['1'];
$params = explode( '_', $magento_pwd_parts['2'] );
if ( ! is_array( $params ) ) {
// Magento password data is not in the expected format
return $check;
}
$seedBytes = $params['1'];
$opsLimit = $params['2'];
$memLimit = $params['3'];
$calculated_hash = calculate_magento_hash($password, $seedBytes, $opsLimit, $memLimit, $salt);
if ( $hash === $calculated_hash ) {
// typed password matches Magento password
// update user password to use this password
wp_set_password( $password, $user_id );
// migration completed for user, delete temporary data
delete_user_meta( $user_id, 'mage_pwd_data' );
return true;
}
return $check;
}
// This is the function from Magento source code to calculate Argon hash.
function calculate_magento_hash($data, $seedBytes, $opsLimit, $memLimit, $salt) {
if (strlen($salt) < SODIUM_CRYPTO_PWHASH_SALTBYTES) {
$salt = str_pad($salt, SODIUM_CRYPTO_PWHASH_SALTBYTES, $salt);
} elseif (strlen($salt) > SODIUM_CRYPTO_PWHASH_SALTBYTES) {
$salt = substr($salt, 0, SODIUM_CRYPTO_PWHASH_SALTBYTES);
}
return bin2hex(
sodium_crypto_pwhash(
$seedBytes,
$data,
$salt,
$opsLimit,
$memLimit,
SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13
)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment