Skip to content

Instantly share code, notes, and snippets.

@prophile
Created March 6, 2014 19:31
Show Gist options
  • Select an option

  • Save prophile/9397574 to your computer and use it in GitHub Desktop.

Select an option

Save prophile/9397574 to your computer and use it in GitHub Desktop.
Some password crypting with PHP
<?php
define('PASSWD_SALT_LENGTH', 16);
define('PASSWD_HASH_ALGORITHM', 'sha512');
define('SALT_LENGTH', 16);
function passwordCrypt($password) {
$saltSource = fopen('/dev/random', 'rb');
$saltData = bin2hex(fread($saltSource, PASSWD_SALT_LENGTH));
fclose($saltSource);
$sourceString = $saltData . $password;
return $saltData . hash(PASSWD_HASH_ALGORITHM, $sourceString);
}
function passwordTest($password, $hash) {
$salt = substr($hash, 0, PASSWD_SALT_LENGTH*2);
$actualHash = substr($hash, PASSWD_SALT_LENGTH*2);
return hash(PASSWD_HASH_ALGORITHM, $salt . $password) == $actualHash;
}
$bees1 = passwordCrypt("bees");
$bees2 = passwordCrypt("bees");
echo "First hash: $bees1\n";
echo "Second hash: $bees2\n";
echo "Test for bees 1: " . (passwordTest("bees", $bees1) ? "MATCH" : "NO MATCH") . "\n";
echo "Test for bees 2: " . (passwordTest("bees", $bees2) ? "MATCH" : "NO MATCH") . "\n";
echo "Bad test for bees 1: " . (passwordTest("faces", $bees1) ? "MATCH" : "NO MATCH") . "\n";
echo "Crypted length: " . strlen($bees1) . "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment