Skip to content

Instantly share code, notes, and snippets.

@thedava
Last active January 9, 2021 20:10
Show Gist options
  • Save thedava/cc114958efe26d25aa8ee01f93b92647 to your computer and use it in GitHub Desktop.
Save thedava/cc114958efe26d25aa8ee01f93b92647 to your computer and use it in GitHub Desktop.
Function to create a save hash for passwords (very hard to brute force)
<?php
define('PASSWORD_ALGO', 'sha512'); // hash will have 128 chars
define('PASSWORD_SALT', 'change_me_pls'); // a static string
define('PASSWORD_CYCLES', 12345); // number between 10.000 and 20.000
define('PASSWORD_DIVERSITY', 3); // number greater than 2
/**
* Generates a save password hash
*
* @param string $password The raw password
* @param string $salt A salt specifically for this user/login
* @return string A hash
*/
function save_hash_password(string $password, string $salt = ''): string {
for ($i = 0; $i < PASSWORD_CYCLES; $i++) {
if ($i % PASSWORD_DIVERSITY == 0) {
$password = hash(PASSWORD_ALGO, $salt . $i . PASSWORD_SALT . $password);
} else {
$password = hash(PASSWORD_ALGO, $password . PASSWORD_SALT . $i . $salt);
}
}
return $password;
}
<?php
/**
* The same logic as the function but as a class
*/
class Hash {
private const PASSWORD_ALGO = 'sha512'; // hash will have 128 chars
private const PASSWORD_SALT = 'change_me_pls'; // a static string
private const PASSWORD_CYCLES = 12345; // number between 10.000 and 20.000
private const PASSWORD_DIVERSITY = 3; // number greater than 2
/**
* Generates a save password hash
*
* @param string $password The raw password
* @param string $salt A salt specifically for this user/login
* @return string A hash
*/
public function createHash(string $password, string $salt = ''): string {
for ($i = 0; $i < self::PASSWORD_CYCLES; $i++) {
if ($i % self::PASSWORD_DIVERSITY == 0) {
$password = hash(self::PASSWORD_ALGO, $salt . $i . self::PASSWORD_SALT . $password);
} else {
$password = hash(self::PASSWORD_ALGO, $password . self::PASSWORD_SALT . $i . $salt);
}
}
return $password;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment