What is the "best" solution these today?
This seems a good option:
https://defuse.ca/php-pbkdf2.htm
But then how about upgrading to PHP5.5 and using this?
http://php.net/manual/en/function.hash-pbkdf2.php
Curious as to why the PHP site states:
Caution
The PBKDF2 method can be used for hashing passwords for storage (it is NIST approved for that use). However, it should be noted that CRYPT_BLOWFISH is better suited for password storage and should be used instead via crypt().
For PHP versions less that 5.5 would it be fair to use the defuse.ca solution, and then just switch it out after upgrading to PHP5.5?
/*
* PBKDF2 key derivation function as defined by RSA's PKCS #5: https://www.ietf.org/rfc/rfc2898.txt
* $algorithm - The hash algorithm to use. Recommended: SHA256
* $password - The password.
* $salt - A salt that is unique to the password.
* $count - Iteration count. Higher is better, but slower. Recommended: At least 1000.
* $key_length - The length of the derived key in bytes.
* $raw_output - If true, the key is returned in raw binary format. Hex encoded otherwise.
* Returns: A $key_length-byte key derived from the password and salt.
*
* Test vectors can be found here: https://www.ietf.org/rfc/rfc6070.txt
*
* This implementation of PBKDF2 was originally created by https://defuse.ca
* With improvements by http://www.variations-of-shadow.com
*/
function pbkdf2($algorithm, $password, $salt, $count, $key_length, $raw_output = false)
{
$algorithm = strtolower($algorithm);
if(!in_array($algorithm, hash_algos(), true))
die('PBKDF2 ERROR: Invalid hash algorithm.');
if($count <= 0 || $key_length <= 0)
die('PBKDF2 ERROR: Invalid parameters.');
$hash_length = strlen(hash($algorithm, "", true));
$block_count = ceil($key_length / $hash_length);
$output = "";
for($i = 1; $i <= $block_count; $i++) {
// $i encoded as 4 bytes, big endian.
$last = $salt . pack("N", $i);
// first iteration
$last = $xorsum = hash_hmac($algorithm, $last, $password, true);
// perform the other $count - 1 iterations
for ($j = 1; $j < $count; $j++) {
$xorsum ^= ($last = hash_hmac($algorithm, $last, $password, true));
}
$output .= $xorsum;
}
if($raw_output)
return substr($output, 0, $key_length);
else
return bin2hex(substr($output, 0, $key_length));
}
This is the current solution from defuse.ca, would it be fair to rename this function to hash_pbkdf2() and after upgrading to PHP5.5 transition would be nice and smooth?
The accepted best practice in PHP passwords, as of PHP 5.5, is password_hash. It presents a single, unified, built-in, future-compatible way to generate a secure password hash.
If you are using a security-updated version of 5.3.x or higher, you can use the password_compat library instead.
Under the covers, the current version makes calls to crypt with some predefined security options. Future versions may change the default options.
Please be sure to carefully read the section on the crypt page that talks about CRYPT_BLOWFISH versioning, as well as review the versioning notes on the password_compat page.
As noted clearly in the warning message, PBKDF2 is accepted by the NIST as an adequate way to store passwords. You can use implementations of it without significant concern, but you should only do so if you either need support for PHP versions prior to 5.3, or need to support PHP versions that have a broken CRYPT_BLOWFISH.
Related
I am working on integrating an API to our web-application. On the initial request, the API returns a response that is encrypted using PBEWithMD5AndTripleDES encryption, and then base 64 encoded. I have an encryption password that is provided to me beforehand. Because of my lack of experience and PBEWithMD5AndTripleDES documentation, I am struggling to decrypt the response. I have tried using phpseclib without any luck.
This is my code with phpseclib
$res = $response->getBody()->getContents();
$res = base64_decode($res);
// this is provided by vendor
$password = self::PASSWORD;
// I tried this too.
//$password = md5(utf8_encode($password), true);
$tripleDes = new TripleDES(TripleDES::MODE_CBC);
$tripleDes->setKey($password);
$ddd = $tripleDes->decrypt($res);
// this is returning false
var_dump($ddd); die();
Can you please provide me some examples of how to use PBEWithMD5AndTripleDES in PHP or point me to some direction or documentation.
PBEWithMD5AndTripleDES uses an MD5 based algorithm for key / IV derivation, which expects a password, a salt and an iteration count as parameters. For encryption TripleDES in CBC mode (des-ede3-cbc) with a 24 bytes key is applied.
PBEWithMD5AndTripleDES is an Oracle proprietary extension of the password-based encryption defined in PKCS#5 (RFC 8018) to support longer keys, here. Because it is proprietary and because of the outdated algorithms like MD5 and the relatively slow TripleDES compared to AES, it should not be used for new implementations, but only for compatibility with legacy code.
I have not found any PHP library on the web that supports PBEWithMD5AndTripleDES out-of-the-box (only for the different PBEWithMD5AndDES, e.g. here). For a custom implementation you actually only need the derivation of the key / IV. So if you don't find an implementation either, but you have compelling reasons to use this algorithm: Here is a Java code that implements the derivation. A port to PHP could be:
function deriveKeyIV($key, $salt, $count){
$result = "";
for ($var = 0; $var < 4; $var++){
if($salt[$var] != $salt[$var + 4])
break;
}
if ($var == 4){
for ($var = 0; $var < 2; $var++){
$tmp = $salt[$var];
$salt[$var] = $salt[3 - $var];
$salt[3 - 1] = $tmp;
}
}
for ($var = 0; $var < 2; $var++){
$toBeHashed = substr($salt, $var * (strlen($salt) / 2), strlen($salt) / 2);
for ($var2 = 0; $var2 < $count; $var2++){
$toBeHashed = hash ("MD5", $toBeHashed . $key, TRUE);
}
$result = $result . $toBeHashed;
}
return $result;
}
The function returns 32 bytes, of which the first 24 bytes are the key and the last 8 bytes are the IV. With this key and IV the encryption with TripleDES in CBC mode can then be performed.
Example:
$keyIv = deriveKeyIV(hex2bin("01026161afaf0102fce2"), hex2bin("0788fe53cc663f55"), 65536);
$key = substr($keyIv, 0, 24);
$iv = substr($keyIv, 24, 8);
print(bin2hex($key) . "\n");
print(bin2hex($iv) . "\n");
print(openssl_encrypt("The quick brown fox jumps over the lazy dog", "des-ede3-cbc", $key, 0, $iv));
Output:
543650085edbbd6c26149c53a57cdd85871fd91c0f6d0be4
d7ffaa69502309ab
m4pye0texirKz1OeKqyKRJ5fSgWcpIPEhSok1SBDzgPthsw9XUuoiqXQBPdsVdUr
As reference I used a Java implementation, more precisely the implementation of PBEWithMD5AndTripleDES of the SunJCE provider, which gives the same result.
Note that the original implementation of PBEWithMD5AndTripleDES only allows a salt that is exactly 8 bytes in size (although the derivation function can handle larger salts), otherwise an exception is thrown (salt must be 8 bytes long). To add this constraint, the following can be added at the beginning of deriveKeyIV:
if (strlen($salt) != 8) {
throw new Exception('Salt must be 8 bytes long');
}
I'm trying to build a simple password generating function using openssl_random_pseudo_bytes and want to know if it is cryptographically strong.
function randomPassword($length = 12) {
mt_srand( hexdec( bin2hex( openssl_random_pseudo_bytes(256) ) ) );
$alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$&*-_=+.?';
$pass = '';
$alphaLength = strlen($alphabet) - 1;
for ($i = 0; $i < $length; $i++) {
$n = mt_rand(0, $alphaLength);
$pass .= $alphabet[$n];
}
return $pass;
}
I would assume that if there is a weakness that is is till in the mt_rand function regardless of seeding it with openssl_random_pseudo_bytes. However, I have been unable to find any discussion on the topic.
According to the documentation
openssl_random_pseudo_bytes is not guaranteed to produce cryptographically strong random data. However, in the improbable case that it was not able to use a cryptographically strong RNG, it will at least tell you. That's what openssl_random_pseudo_bytes's second parameter is for:
It also indicates if a cryptographically strong algorithm was used to produce the pseudo-random bytes, and does this via the optional crypto_strong parameter. It's rare for this to be FALSE, but some systems may be broken or old.
You can pass this parameter and then check its value:
$bytes = openssl_random_pseudo_bytes(256, $strong);
if (!$strong) {
// handle error as necessary.
}
However, opposed to openssl_random_pseudo_bytes, mt_rand is explicitly stated to not produce cryptographically secure values.
This function does not generate cryptographically secure values, and should not be used for cryptographic purposes.
I'm no expert, but I doubt that seeding a Mersenne Twister with secure random data would make the generated data any more secure (if at all, probably just the first byte):
Counter-suggestion
You did not state which version of PHP you're using. If you are using PHP 7, random_int might make a good alternative for you (it's also explicitly stated to be cryptographically secure):
for ($i = 0; $i < $length; $i++) {
$n = random_int(0, $alphaLength);
$pass .= $alphabet[$n];
}
Alternatively, this answer provides a secure, PHP-based implementation for a rand function that uses OpenSSL as an CSPRNG that you could use in place of random_int.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I'm using the below functions to help me create a hashed and salted password encryption. I can't using password_hash because I'm running PHP 5.3.
My process:
Generate salt
Generate hash from user created password ie ('password') and salt
Store returned value of create_hash in database in password field. I could separate the salt and hash into two separate fields in the db, but I'm not sure there's a need security wise because if access to my database was gained, access to both the fields would be available and no more secure than storing the 4 component string returned by create_hash, correct?
When user tries to log in, compare the password they enter into the form to the value stored in the database using the validate_password function and if that passes generate a session
Prevent any kind of brute force attack by limiting login attempts to 10 per session? Is this necessary/good practice?
Code:
<?php
/*
* Password Hashing With PBKDF2 (http://crackstation.net/hashing-security.htm).
* Copyright (c) 2013, Taylor Hornby
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
// These constants may be changed without breaking existing hashes.
define("PBKDF2_HASH_ALGORITHM", "sha256");
define("PBKDF2_ITERATIONS", 1000);
define("PBKDF2_SALT_BYTE_SIZE", 24);
define("PBKDF2_HASH_BYTE_SIZE", 24);
define("HASH_SECTIONS", 4);
define("HASH_ALGORITHM_INDEX", 0);
define("HASH_ITERATION_INDEX", 1);
define("HASH_SALT_INDEX", 2);
define("HASH_PBKDF2_INDEX", 3);
function create_salt() {
return base64_encode(mcrypt_create_iv(PBKDF2_SALT_BYTE_SIZE, MCRYPT_DEV_URANDOM));
}
function create_hash($password, $salt)
{
// format: algorithm:iterations:salt:hash
return PBKDF2_HASH_ALGORITHM . ":" . PBKDF2_ITERATIONS . ":" . $salt . ":" .
base64_encode(pbkdf2(
PBKDF2_HASH_ALGORITHM,
$password,
$salt,
PBKDF2_ITERATIONS,
PBKDF2_HASH_BYTE_SIZE,
true
));
}
function validate_password($password, $correct_hash)
{
$params = explode(":", $correct_hash);
if(count($params) < HASH_SECTIONS)
return false;
$pbkdf2 = base64_decode($params[HASH_PBKDF2_INDEX]);
return slow_equals(
$pbkdf2,
pbkdf2(
$params[HASH_ALGORITHM_INDEX],
$password,
$params[HASH_SALT_INDEX],
(int)$params[HASH_ITERATION_INDEX],
strlen($pbkdf2),
true
)
);
}
// Compares two strings $a and $b in length-constant time.
function slow_equals($a, $b)
{
$diff = strlen($a) ^ strlen($b);
for($i = 0; $i < strlen($a) && $i < strlen($b); $i++)
{
$diff |= ord($a[$i]) ^ ord($b[$i]);
}
return $diff === 0;
}
/*
* PBKDF2 key derivation function as defined by RSA's PKCS #5: https://www.ietf.org/rfc/rfc2898.txt
* $algorithm - The hash algorithm to use. Recommended: SHA256
* $password - The password.
* $salt - A salt that is unique to the password.
* $count - Iteration count. Higher is better, but slower. Recommended: At least 1000.
* $key_length - The length of the derived key in bytes.
* $raw_output - If true, the key is returned in raw binary format. Hex encoded otherwise.
* Returns: A $key_length-byte key derived from the password and salt.
*
* Test vectors can be found here: https://www.ietf.org/rfc/rfc6070.txt
*
* This implementation of PBKDF2 was originally created by https://defuse.ca
* With improvements by http://www.variations-of-shadow.com
*/
function pbkdf2($algorithm, $password, $salt, $count, $key_length, $raw_output = false)
{
$algorithm = strtolower($algorithm);
if(!in_array($algorithm, hash_algos(), true))
trigger_error('PBKDF2 ERROR: Invalid hash algorithm.', E_USER_ERROR);
if($count <= 0 || $key_length <= 0)
trigger_error('PBKDF2 ERROR: Invalid parameters.', E_USER_ERROR);
if (function_exists("hash_pbkdf2")) {
// The output length is in NIBBLES (4-bits) if $raw_output is false!
if (!$raw_output) {
$key_length = $key_length * 2;
}
return hash_pbkdf2($algorithm, $password, $salt, $count, $key_length, $raw_output);
}
$hash_length = strlen(hash($algorithm, "", true));
$block_count = ceil($key_length / $hash_length);
$output = "";
for($i = 1; $i <= $block_count; $i++) {
// $i encoded as 4 bytes, big endian.
$last = $salt . pack("N", $i);
// first iteration
$last = $xorsum = hash_hmac($algorithm, $last, $password, true);
// perform the other $count - 1 iterations
for ($j = 1; $j < $count; $j++) {
$xorsum ^= ($last = hash_hmac($algorithm, $last, $password, true));
}
$output .= $xorsum;
}
if($raw_output)
return substr($output, 0, $key_length);
else
return bin2hex(substr($output, 0, $key_length));
}
?>
I can't using password_hash because I'm running PHP 5.3
Yes, you can. https://github.com/ircmaxell/password_compat
Barring that, you can use the same algorithm - bcrypt. How do you use bcrypt for hashing passwords in PHP?
It should also be noted that PHP 5.3 was end-of-lifed 7 months ago, making it dangerous to run in production. Chances are it contains a number of security holes, and that'll only continue to get worse. EOL means time to upgrade.
Here's the function I'm using to generate random salts:
function generateRandomString($nbLetters){
$randString="";
$charUniverse="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
for($i=0; $i<$nbLetters; $i++){
$randInt=rand(0,61);
$randChar=$charUniverse[$randInt];
$randString=$randomString.$randChar;
}
return $randomString;
}
This is for a non commercial website. It's only used to generate the salt (to be stored in the db and used along with the user submitted pw for hashing).
Is this appropriate? Should I use a larger subset of characters, and if so is there an easy way to do that in PHP?
If you are hashing passwords, you should use a modern hashing algorithm that does not require you to generate your own salt. Using weak hashing algorithms presents a danger to both you and your users. My original answer was written eight years ago. Times have changed, and password hashing is a lot easier now.
You should always use built in functions to hash/check passwords. Using your own algorithms at any point introduces a huge amount of unnecessary risk.
For PHP, consider using password_hash(), with the PASSWORD_BCRYPT algorithm. There is no need to provide your own salt.
Below is my original answer, for posterity:
Warning: The following implementation does not produce an unpredictable salt, as per the documentation for uniqid.
From the php sha1 page:
$salt = uniqid(mt_rand(), true);
This looks simpler, and more effective (since each is unique) than what you have proposed.
If you're on Linux, /dev/urandom is probably your best source of randomness. It's supplied by the OS itself, so it's guaranteed to be much more reliable than any PHP built-in function.
$fp = fopen('/dev/urandom', 'r');
$randomString = fread($fp, 32);
fclose($fp);
This will give you 32 bytes of random blob. You'll probably want to pass this through something like base64_encode() to make it legible. No need to juggle characters yourself.
Edit 2014: In PHP 5.3 and above, openssl_random_pseudo_bytes() is the easiest way to get a bunch of random bytes. On *nix systems, it uses /dev/urandom behind the scenes. On Windows systems, it uses a different algorithm that is built into the OpenSSL library.
Related: https://security.stackexchange.com/questions/26206
Related: should i use urandom or openssl_random_pseudo_bytes?
password_hash() is availble in PHP 5.5 and newer. I am surprised to learn it is not mentioned here.
With password_hash() there is no need to generate a salt as the salt is automatically being generated using the bcrypt algorithm -- and therefore no need to make up a set of characters.
Instead, the user-submitted password is compared to the unique password hash stored in the database using password_verify(). Just store Username and Password hash in the user database table, you will then be able to compare it to a user-submitted password using password_verify().
How password hash()'ing works:
The password_hash() function outputs a unique password hash, when storing the string in a database -- it is recommended that the column allows up to 255 characters.
$password = "goat";
echo password_hash($password, PASSWORD_DEFAULT);
echo password_hash($password, PASSWORD_DEFAULT);
echo password_hash($password, PASSWORD_DEFAULT);
// Output example (store this in the database)
$2y$10$GBIQaf6gEeU9im8RTKhIgOZ5q5haDA.A5GzocSr5CR.sU8OUsCUwq <- This hash changes.
$2y$10$7.y.lLyEHKfpxTRnT4HmweDKWojTLo1Ra0hXXlAC4ra1pfneAbj0K
$2y$10$5m8sFNEpJLBfMt/3A0BI5uH4CKep2hiNI1/BnDIG0PpLXpQzIHG8y
To verify a hashed password, you use password_verify():
$password_enc = password_hash("goat", PASSWORD_DEFAULT);
dump(password_verify('goat', $password_enc)); // TRUE
dump(password_verify('fish', $password_enc)); // FALSE
If you prefer, salt can be added manually as an option, like so:
$password = 'MyPassword';
$salt = 'MySaltThatUsesALongAndImpossibleToRememberSentence+NumbersSuch#7913';
$hash = password_hash($password, PASSWORD_DEFAULT, ['salt'=>$salt]);
// Output: $2y$10$TXlTYWx0VGhhdFVzZXNBT.ApoIjIiwyhEvKC9Ok5qzVcSal7T8CTu <- This password hash not change.
Replace rand(0,61) with mt_rand(0, 61) and you should be fine (Since mt_rand is better at producing random numbers)...
But more important than strength of the salt is the way you hash it. If you have a great salt routine, but only do md5($pass.$salt), you're throwing away the salt. I personally recommend stretching the hash... For example:
function getSaltedHash($password, $salt) {
$hash = $password . $salt;
for ($i = 0; $i < 50; $i++) {
$hash = hash('sha512', $password . $hash . $salt);
}
return $hash;
}
For more information on hash stretching, check out this SO answer...
I would take advice from another answer and use mt_rand(0, 61), because the Mersenne Twister produces better entropy.
Additionally, your function is really two parts: generating random $nbLetters digits and encoding that in base62. This will make things much clearer to a maintenance programmer (maybe you!) who stumbles across it a few years down the road:
// In a class somewhere
private $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private function getBase62Char($num) {
return $chars[$num];
}
public function generateRandomString($nbLetters){
$randString="";
for($i=0; $i < $nbLetters; $i++){
$randChar = getBase62Char(mt_rand(0,61));
$randString .= $randChar;
}
return $randomString;
}
This is my method, It uses truly random numbers from atmospheric noise. It is all mixed in with pseudo-random values and strings. Shuffled and hashed. Here is my code: I call it overkill.
<?php
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
function get_true_random_number($min = 1, $max = 100) {
$max = ((int) $max >= 1) ? (int) $max : 100;
$min = ((int) $min < $max) ? (int) $min : 1;
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => '',
CURLOPT_USERAGENT => 'PHP',
CURLOPT_AUTOREFERER => true,
CURLOPT_CONNECTTIMEOUT => 120,
CURLOPT_TIMEOUT => 120,
CURLOPT_MAXREDIRS => 10,
);
$ch = curl_init('http://www.random.org/integers/?num=1&min='
. $min . '&max=' . $max . '&col=1&base=10&format=plain&rnd=new');
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
curl_close($ch);
if(is_numeric($content)) {
return trim($content);
} else {
return rand(-10,127);
}
}
function generateSalt() {
$string = generateRandomString(10);
$int = get_true_random_number(-2,123);
$shuffled_mixture = str_shuffle(Time().$int.$string);
return $salt = md5($shuffled_mixture);
}
echo generateSalt();
?>
The atmospheric noise is provided by random.org. I have also seen truly random generation from images of lava lamps that are interpreted via hue and location. (Hue is location)
Here is a much better way if you have windows and cant do /dev/random.
//Key generator
$salt = base64_encode(openssl_random_pseudo_bytes(128, $secure));
//The variable $secure is given by openssl_random_ps... and it will give a true or false if its tru then it means that the salt is secure for cryptologic.
while(!$secure){
$salt = base64_encode(openssl_random_pseudo_bytes(128, $secure));
}
I think that a very good salt for example is the user name (if you are talking about pw hashing and the user name doesn't change.)
You don't need to generate anything and don't need to store further data.
A fairly simple technique:
$a = array('a', 'b', ...., 'A', 'B', ..., '9');
shuffle($a);
$salt = substr(implode($a), 0, 2); // or whatever sized salt is wanted
Unlike uniqid() it generates a random result.
I use this:
$salt = base64_encode(mcrypt_create_iv(PBKDF2_SALT_BYTES, MCRYPT_DEV_URANDOM));
If you want ultimate unique salt you should use a unique value entered and required by the user such as the email or the username, then hashing it using sha1 and then merge it - concatenate - with the salt value generated by your code.
Another, you have to extend $charUniverse by the mean of some special characters such as #,!#- etc.
I have been trying to make my users passwords really secure using pbkdf2.
The password hash goes into the database fine, but the salt is not.
It seems the salt contains exotic characters that the mysql column doesnt like.
All columns in my 'users' table are UTF8_unicode_ci.
Here is my password hasher:
$size = mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CFB);
$salt = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
$passHash = pbkdf2('SHA512', $pass, $salt, 8192, 256) ;
include("dbconnect.php") ;
$result = $dbh->prepare("INSERT INTO users (name, email, qq, password, salt)VALUES(?, ?, ?, ?, ?)") ;
$result->bindParam(1, $name, PDO::PARAM_STR) ;
$result->bindParam(2, $email, PDO::PARAM_STR) ;
$result->bindParam(3, $qq, PDO::PARAM_STR) ;
$result->bindParam(4, $passHash, PDO::PARAM_STR) ;
$result->bindParam(5, $salt, PDO::PARAM_STR) ;
$result->execute() ;
And the pbkdf2:
/*
* PBKDF2 key derivation function as defined by RSA's PKCS #5: https://www.ietf.org/rfc/rfc2898.txt
* $algorithm - The hash algorithm to use. Recommended: SHA256
* $password - The password.
* $salt - A salt that is unique to the password.
* $count - Iteration count. Higher is better, but slower. Recommended: At least 1000.
* $key_length - The length of the derived key in bytes.
* $raw_output - If true, the key is returned in raw binary format. Hex encoded otherwise.
* Returns: A $key_length-byte key derived from the password and salt.
*
* Test vectors can be found here: https://www.ietf.org/rfc/rfc6070.txt
*
* This implementation of PBKDF2 was originally created by https://defuse.ca
* With improvements by http://www.variations-of-shadow.com
*/
function pbkdf2($algorithm, $password, $salt, $count, $key_length, $raw_output = false){
$algorithm = strtolower($algorithm);
if(!in_array($algorithm, hash_algos(), true))
die('PBKDF2 ERROR: Invalid hash algorithm.');
if($count <= 0 || $key_length <= 0)
die('PBKDF2 ERROR: Invalid parameters.');
$hash_length = strlen(hash($algorithm, "", true));
$block_count = ceil($key_length / $hash_length);
$output = "";
for($i = 1; $i <= $block_count; $i++) {
// $i encoded as 4 bytes, big endian.
$last = $salt . pack("N", $i);
// first iteration
$last = $xorsum = hash_hmac($algorithm, $last, $password, true);
// perform the other $count - 1 iterations
for ($j = 1; $j < $count; $j++) {
$xorsum ^= ($last = hash_hmac($algorithm, $last, $password, true));
}
$output .= $xorsum;
}
if($raw_output)
return substr($output, 0, $key_length);
else
return bin2hex(substr($output, 0, $key_length));
}
Also, I have just noticed that it is storing totally different hashes for passwords that are the same.
Am I doing this right?
It's hard to give an exact answer to a question as broad as 'Am I doing this right?' I can say that the entire point of salting passwords before hashing is so that the resultant hash will be unique between users. So getting different output for the same input is a good thing. Look up 'dictionary attack' for more information on why.
As to your code, it sounds like what you really want to know is why your salt isn't getting stored to the database. Debugging steps I can think of, without more specific details
$salt could be false, mcrypt_create_iv returns false on error (unlikely because of the hash output differences you mentioned above, but worth checking.
Output characters are not recognized as you suspect. You could try converting the database column types to varbinary and using a string to binary or hex decoder before adding to your prepare.
Try experimenting with column types with different character encodings and see what column type your salts can go into. UTF-8 uses a variable number of bytes for each character, which makes me uncomfortable when dealing with things that are absolutes. A salt and a hash are generally considered to be fixed-with bit fields, often expressed in hex format for convenience.
I might be able to narrow down a problem if you provided your server environment, php version, mysql version etc. and a few samples of salts which aren't being stored correctly.
You should convert the result into base64 encoding before storing to a varchar column. Base64 encoding basically converts an array of bytes into something in the ASCII range of displayable (and therefore SQL storable) characters.