Skip to content

Instantly share code, notes, and snippets.

@cballou
Created March 25, 2012 14:17
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cballou/2195438 to your computer and use it in GitHub Desktop.
Save cballou/2195438 to your computer and use it in GitHub Desktop.
Securing Your PHP Sessions with a Random Salt (old, use bcrypt)
CREATE secure_login (
`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`email` VARCHAR(120) NOT NULL,
`salt` VARCHAR(8) NOT NULL,
`password` VARCHAR(40) NOT NULL,
`session` VARCHAR(40) DEFAULT NULL,
`disabled` TINYINT(1) UNSIGNED DEFAULT 0,
`created_dt` DATETIME DEFAULT '0000-00-00 00:00:00',
`modified_ts` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE INDEX `uniq_idx` (`email`)
) ENGINE=InnoDB CHARSET=UTF8;
<?php
function create_hash($string, $hash_method = 'sha1', $salt_length = 8) {
// generate random salt
$salt = randomSalt($salt_length);
if (function_exists('hash') && in_array($hash_method, hash_algos()) {
return hash($hash_method, $salt . $string);
}
return sha1($salt . $string);
}
<?php
/**
* @param string $pass The user submitted password
* @param string $hashed_pass The hashed password pulled from the database
* @param string $salt The salt pulled from the database
* @param string $hash_method The hashing method used to generate the hashed password
*/
function validateLogin($pass, $hashed_pass, $salt, $hash_method = 'sha1') {
if (function_exists('hash') && in_array($hash_method, hash_algos()) {
return ($hashed_pass === hash($hash_method, $salt . $pass));
}
return ($hashed_pass === sha1($salt . $pass));
}
<?php
function randomSalt($len = 8) {
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`~!@#$%^&*()-=_+';
$l = strlen($chars) - 1;
$str = '';
for ($i = 0; $i &lt; $len; ++$i) {
$str .= $chars[rand(0, $l];
}
return $str;
}
@itisnot-me
Copy link

I know its old but here

https://gist.github.com/cballou/2195438#file-pseudo-random-salt-generator-php

for ($i = 0; $i < $len; ++$i) {
        $str .= $chars[rand(0, $l)];
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment