Skip to content

Instantly share code, notes, and snippets.

@kiler129
Created August 12, 2015 18:33
Show Gist options
  • Save kiler129/f7e1c0ccb94d12cbcd85 to your computer and use it in GitHub Desktop.
Save kiler129/f7e1c0ccb94d12cbcd85 to your computer and use it in GitHub Desktop.
Hashing password via PHP or MySQL
<?php
//This is only demonstration of really bad bad bad password storing idea - do NOT ever use that.
//Test was used only to prove that hashing on database is not only less secure but slower.
define('NUMBER_OF_USERS', 50000);
define('PASSWORD_LENGTH_FROM', 10);
define('PASSWORD_LENGTH_TO', 100);
/*
Database
--------
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL,
`user_salt` varchar(16) CHARACTER SET ascii NOT NULL,
`pass` varchar(32) CHARACTER SET ascii NOT NULL
) ENGINE=MEMORY DEFAULT CHARSET=latin1;
ALTER TABLE `users` ADD PRIMARY KEY (`id`);
ALTER TABLE `users` MODIFY `id` int(10) unsigned NOT NULL AUTO_INCREMENT;
*/
$randomSource = fopen('/dev/urandom', 'r');
stream_set_blocking($randomSource, 0);
//Generate user salts & passwords
$salts = $passwords = [];
for($i=0; $i<NUMBER_OF_USERS; $i++) {
$salts[$i] = unpack('H*', fread($randomSource, 8))[1];
if(!isset($salts[$i][15])) {
die("Entropy too low - failed to generate salts at $i\n");
}
$length = round(rand(PASSWORD_LENGTH_FROM, PASSWORD_LENGTH_TO) / 2);
$passwords[$i] = unpack('H*', fread($randomSource, $length))[1];
if(!isset($passwords[$i][$length*2-1])) {
die("Entropy too low - failed to generate passwords at $i\n");
}
}
//Let's have some database stuff
$dbh = new PDO('mysql:host=127.0.0.1:3306;dbname=speed', 'root', '');
$plainQuery = $dbh->prepare('INSERT INTO `users` (`user_salt`, `pass`) VALUES (:salt, :pass)');
$dbh->exec('TRUNCATE users');
/**********************************************************************************************************************/
/**********************************************************************************************************************/
$s = microtime(true);
foreach($salts as $i => $salt) {
$plainQuery->execute(['salt' => $salt, 'pass' => md5($salt . $passwords[$i])]);
}
$e = microtime(true);
echo 'Test for plain query finished, took ' . round(($e-$s)*1000, 2) . "ms\n";
$dbh->exec('TRUNCATE users');
/**********************************************************************************************************************/
$dumbassQuery = $dbh->prepare('INSERT INTO `users` (`user_salt`, `pass`) VALUES (:salt, MD5(CONCAT(:salt, :pass)))');
$s = microtime(true);
foreach($salts as $i => $salt) {
$dumbassQuery->execute(['salt' => $salt, 'pass' => $passwords[$i]]);
}
$e = microtime(true);
echo 'Test for dumbass query finished, took ' . round(($e-$s)*1000, 2) . "ms\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment