Skip to content

Instantly share code, notes, and snippets.

@jlogsdon
Created December 13, 2010 15:55
Show Gist options
  • Save jlogsdon/739134 to your computer and use it in GitHub Desktop.
Save jlogsdon/739134 to your computer and use it in GitHub Desktop.
<?php
/**
* CREATE TABLE `accounts` (
* `id` INT AUTO INCREMENT,
* `login` VARCHAR(50) NOT NULL,
* `password` VARCHAR(64) NOT NULL,
* `salt` VARCHAR(14) NOT NULL,
* PRIMARY KEY (`id`),
* INDEX (`login`, `password`);
* );
*/
// Generate a random salt between 10 and 14 characters long
function generateSalt() {
// seed the random function so it's at least a bit more random
mt_srand(microtime(true));
$length = mt_rand(10, 14);
$salt = null;
// these are the characters used in a salt
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()';
// generate the salt
for ($i = 0; $i < $length; $i++) {
$salt .= $chars[mt_rand(0, strlen($chars) - 1)];
}
return $salt;
}
function loginCheck($login, $password) {
// select a row from the table using the login
$account = fetch_first_row('select * from accounts where login like "$1"', $login);
// if no row, login doesn't exist
if (!$account) {
return false;
}
// compute the hash and compare
$hash = hash('sha256', $login . $password . $account['salt']);
return ($hash == $account['password']);
}
function loginCreate($login, $password) {
$salt = generateSalt();
$hash = hash('sha256', $login . $password . $salt);
// save the new account. you will want to check for the login before creating to prevent
// duplicates, of course
insert_into('accounts', compact('login', 'password', 'salt'));
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment