PHP - Secure Password Salt And Hashing: Blowfish
<?php function cryptPass($input, $rounds = 9){ $salt = ""; $saltChars = array_merge(range('A','Z'), range('a','z'), range(0,9)); for($i = 0; $i < 22; $i++){ $salt .= $saltChars[array_rand($saltChars)]; } return crypt($input, sprintf('$2y$%02d$', $rounds) . $salt); } echo $inputPass = "password2"; echo $pass = "password"; $hashedPass = cryptPass($pass); echo $hashedPass; if(crypt($inputPass, $hashedPass) == $hashedPass){ echo "<br /><h1>Password is a match = log user in</h1>"; }else{ echo "<br />Password does not match = do not log in"; } ?>My PHP version 5.2 When I run above code I am getting the password match answer. I should have get error message. Can anyone advise me . Thank you. Similar TutorialsI am currently testing a small hash idea, for say database encryption for passwords. Basically what I want to know is if this is a good or not the best method for encryption... Code: [Select] <?php $us_password = 'drowssap'; // User-Submitted Password; $salt = '))!&8d*34d763!(('; //The salt $dbs_password = '3750221c513902ff76f4ec7ffed5fa4385d2599d'; // Sha1 hash for "drowssap"+Salt; if($us_password == sha1($us_password.$salt)){ //Some other code for success here } else { //Failure code here } ?> So basically, this is an abstract example of what I'm doing... Is it any good, or what could be improved? I've also used DB-Stored salts unique to each user, so even if someone used rainbow tables ( even after failure on my part for letting them get the hash... ), and multiple users had the same password, they would only crack one, rather than all of them, since the hashes would be different due to the different salts. Just a quick question. I have heard a few people say that they store a specific (maybe random) salt string in the same row as the user that is generated when the user account is created or password is changed. But I thought one of the reasons people use hashing is so if someone managed to get hold of the database they couldn't decipher the password (like a simple md5'd string). But putting the salt string next to the username surely gives the attacker a major push in the right direction? I am not claiming to know anything, I'm just asking because I'm trying to find the best practice (Or at least a good tried and tested one). I like the idea of having a salt in a php config file, because that would mean an attacker would actually have to get your files, and if they had got that far then your pretty much screwed anyway.
{ I am trying to use this code for password hashing for every time that password is hashed it returns a different value. How do I save the hashed value in database ? When to use password_needs_rehash
Workflow for account registration.
1. The user creates an account.
2. Their password is hashed password_hash($password, PASSWORD_DEFAULT) and stored in the database.
3. When the user attempts to login, the hash (password_verify ) of the password they entered is checked against the hash of their real password (retrieved from the database).
4. If the hashes match, the user is granted access. If not, the user is told they entered invalid login credentials.
My question is
1. When should I call password_needs_rehash?
2. Do I really need to use it?
Hello I've recently been made aware that I need to hash the token I use when allowing users to reset their password. I have a working solution but I'm hoping someone could let me know if this is an adequate way of doing it; 1. User enters their email, I check whether their actually a member and then... create a passcode (1) create a salt (2) hash them together to create a passcode_hash (3) insert the (2) and (3) into the database send an email to the user with a link using (1) and the userid in the address 2. When the link is followed... $_GET the userid and lookup the salt and passcode_hash for that id hash together the passcode in the URL with the salt, and compare that to passcode_hash if that is successfull then allow an update of the password (show the update form) 3. The password update form is sent along with two hidden fields (the passcode and userid from the URL) On the form processing script I perform the same check as on Step 2 to check the passcode and user id have not been messed with Update the password and delete the passcode Hopefully that makes sense... is that correct? Here is my code that compares the passcode with the passcode_hash.... // get the passcode and email from URL (I will sanitize these) $passcode = $_GET['passcode']; $member_id = $_GET['uid']; // find the salt associated with the userid $stmt = $db->prepare("SELECT passcode,salt FROM members_verify WHERE members_id = ?"); $stmt->bind_param('i',$member_id); $stmt->execute(); $stmt->bind_result($db_passcode,$salt); $stmt->fetch(); $stmt->close(); // Create salted password $passcode_hash = hash('sha512', $passcode . $salt); if($passcode_hash===$db_passcode){ $allowUpdate = 'yes'; }Any advice would be great Edited by paddyfields, 07 June 2014 - 08:18 AM. I'm still trying to figure out why I should use salt. If the bad guy knows a name and tries something like brute force shoving passwords into the log-in form until one worked how would salt help stop that? If a bad guy, God forbid, gets hold of the user names and passwords like they did phpbb(?) forums several years ago how would salt stop that? I know I may be beating this issue to death but if I have salt in the users table assigned to a user and his password now equals $stored_password = sha1($salt.$password) does this really doesn't matter? Because if the bad guy knows the user name and uses brute force or has a list of passwords from the users table that he has gotten some way. All he has to do is type in the user name and password and salt will be added automatically. Used to be a good option, but don't know anymore as password_hash() is now available.
Agree?
I understand that I shouldn't ever manually salt and disable the functions salting. That being said, is there any reason to add a bit extra to the user's password (such as an internal ID and some random constant)?
Hi, I am limbo with this one. What I have makes sense to me, but I know I'm missing something or doing something wrong I have been able to hash passwords with salt by new people registering to my site by doing this: if(!$error) { $alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcedfghijklmnopqrstuvwxyz1234567890"; $rand = str_shuffle($alpha); $salt = substr($rand,0,40); $hashed_password = sha1($salt . $_POST['password']); $query = "INSERT INTO `cysticUsers` ( `FirstName`, `LastName`, `Email`, `Password`, `salt`, `RelationshipToCF`, `State`, `Gender`, `Birthday`, `Status` )VALUES( '" . mysql_real_escape_string($_POST['firstName']) . "', '" . mysql_real_escape_string($_POST['lastName']) . "', '" . mysql_real_escape_string($_POST['email']) . "', '" . $hashed_password . "', '" . $salt . "', '" . mysql_real_escape_string($_POST['RelationToCF']) . "', '" . mysql_real_escape_string($_POST['State']) . "', '" . mysql_real_escape_string($_POST['sex']) . "', '" . mysql_real_escape_string($_POST['DateOfBirth_Year'] . "-" . $_POST['DateOfBirth_Month'] . "-" . $_POST['DateOfBirth_Day']) . "', 'pending' )"; mysql_query($query, $connection); I have been able to to update EXISTING users passwords by doing this: $query = "SELECT * FROM `cysticUsers`"; $request = mysql_query($query,$connection); while($result = mysql_fetch_array($request)) { $alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcedfghijklmnopqrstuvwxyz1234567890"; $rand = str_shuffle($alpha); $salt = substr($rand,0,40); $hashed_password = sha1($salt . $result['Password']); $user = $result['id']; $query2 = "UPDATE `cysticUsers` SET `salt` = '$salt' WHERE `id` = '$user'"; $request2 = mysql_query($query2,$connection) or die(mysql_error()); $query3 = "UPDATE `cysticUsers` SET `encrypted_passwords` = '$hashed_password' WHERE `id` = '$user'"; $request3 = mysql_query($query3,$connection) or die(mysql_error()); } Now, I want to be able to SIGN BACK IN with the existing password and I am failing miserably by doing this: $query = "SELECT `salt`,`id`,`email`,`password` FROM `cysticUsers` WHERE `Email` = '" . $email . "' AND `Password` = '" . $password . "' && `Status` = 'active' LIMIT 1"; $request = mysql_query($query,$connection) or die(mysql_error()); $email = mysql_real_escape_string($_POST['email']); $password = mysql_real_escape_string($_POST['password']); if(@mysql_num_rows($request)) { $row = mysql_fetch_assoc($request); if (sha1($row['salt'] . $_POST['password']) === $row['Password']) { $_SESSION['CLIFE']['AUTH'] = true; $_SESSION['CLIFE']['ID'] = $result['id']; // UPDATE LAST ACTIVITY FOR USER $query = "UPDATE `cysticUsers` SET `LastActivity` = '" . date("Y-m-d") . " " . date("g:i:s") . "' WHERE `id` = '" . mysql_real_escape_string($_SESSION['CLIFE']['ID']) . "' LIMIT 1"; mysql_query($query,$connection); if(!empty($_POST['return'])) { header("Location: " . $_POST['return']); }else{ header("Location: CysticLife-Dashboard.php?id=" . $_SESSION['CLIFE']['ID']); } } }else{ $_SESSION['CLIFE']['AUTH'] = false; $_SESSION['CLIFE']['ID'] = false; } } I've been scouring resources and am stuck on this. I have a deadline to meet that I am behind on. Needless to say I'm pulling my hair out and some help with this would be GREATLY appreciated. Thank you in advance! Hello. I have a few questions about the hashing methods available. I have read plenty of articles on the net about how MD5 and SHA0/SHA1 are not ideal methods to hash your data. PHP.net has recommended crypt() or hash(), but I am curious if salting even protects your users passwords? I know salting protects against rainbow tables ... but is there no way to defend against Brute Force or Dictionary Attacks? Anyways. What do you guys recommend I use just to make sure my user's password's are not ... compromised. I guess the first-layer of defense would be to make sure your database passwords are secure and under a DMZ. But solutions like that including IDS / Firewall are ranging between $2500-$5000 a month. Any help would be greatly appreciated. Thank you. Part of my class: using PHP5 ( http://php.net/manua...ssword-hash.php) If you know of anything new in PHP5 related to please do share
protected function create_hash($string){ $password = "#" . strrev($password); $grs = $this->grs("|WordToTheWise",rand(22, 50)); $hash = password_hash("_" . strrev($string), PASSWORD_BCRYPT, array('cost'=>rand(4,14),'salt'=>$grs)); return strrev($hash); } public function verifyhash($string, $hash_string){//verifies that the hash is equal to the password return (password_verify("_" . strrev($string), strrev($hash_string)) ? true : false); } private function grs($string_append = "", $length = 22) { $length = $length - strlen($string_append); $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&()_*,./;[]|'; $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, strlen($characters) - 1)]; } return $randomString . $string_append; }Okay so u use strrev on my string and hash just to make everything a bit more CONFUSING and i append the string with a "]" just to make the password harder to brute the strrev and append string is not meant to make the hash any more secure. I store the reversed hash in my DB as a varchar The point of the reverse hash is only to make the hash a little more unrecognizable to the human eye. The Const is randomly chosen 4 - 14, and the salt is randomly generated with a special string appended. How would you improve the hashing? Edited by Richard_Grant, 09 September 2014 - 11:48 PM. What is the latest and greatest way to hash data in PHP? Hello all, I looked everytwhere to find the answer to my question bug so far, no luck. I hope someone here can help me with this issue. Oke, my problem is as following. I'm creating a string with a foreach loop that I then will has after the loop. The problem is, is that that string is addad to a variable. When I sha1 hash that variable with the sha1 function from within PHP I get a different hash as when I just echo the string and manually hash that. The point is, is that the manually hashed string is then correct, and the automitically hash string isn't. This is the code I'm using, can someone tell me where to look at to solve this problem? if (is_array($this->getFormData())){ foreach ($this->getFormData() as $name => $value) { $string .= $name."=".$value.$shamethod; } } $hashstring = sha1($string, false); echo '<br /><br />'.$hashstring.'<br /><br />'; echo $string; Thanks for your time. Dok Ok this is my script so far: Code: [Select] class User { function generateHash($password, &$saluti=null) { define('SALT_LENGTH', 15); $key = '!@#$%^&*()_+=-{}][;";/?<>.,'; if ($saluti=="") { $saluti = substr(hash('sha512', uniqid(rand(), true).$key.microtime()), 0, SALT_LENGTH); } else { $saluti = substr($saluti, 0, SALT_LENGTH); } return hash('sha512', $saluti . $key . $password); } function validate_user($username,$password) { $mysql = new Database(); $hashedPassword = generateHash($password,''); $ensure_credentials = $mysql->verify_username_and_password($username,$hashedPassword); if($ensure_credentials) { $_SESSION['auth'] == "yes"; header("Location: index.php"); } else return "That was not the correct username or password."; } } It gives me this error: Quote [05-Feb-2012 17:14:59] PHP Fatal error: Call to undefined function generatehash() in /home1/elvonica/public_html/scripts/classes/user.php on line 24 Can anyone help me solve this? which would be secured to use friends? or could we use both together? show some usage example please I honestly don't think salt is necessary with my system. I currently use: $password = md5(sha1(md5(sha1($_POST['password'])))); Is this good enough when it comes to storing a password, encrypted? I have a large number of files. It is recommended to save the files with hashing system to have fast access to files through the OS. But I have no practical knowledge about hash. Could you please give me a hint, how to save a file with hash coded system via php? and how to read the hash coded filename by php? Thank you in advance! Hi everyone I'm new around here but thought it's about time I joined a good PHP forum! I'll introduce myself properly on the right section, but for now, I'll my post my coding problem on here. I wonder if any has any knowledge or can help. I'm setting up a connection from my web server to a potential data supplier web server, which involves a load of encryption. One of the stages is generating a SHA1 hash of an encrypted string. Now I've got some old example code, however the "mhash" function used in this old code appears to obsolete. Thus is doesn't work. I've tried using the available "sha1" and "hash" functions but cannot replicate the hashed output they provide. Here's the original code: Code: [Select] $encrypted_string = "B0436CBFBC5CAAFB7339AF4A1DF845974D53B9D369146E2E4F1451929D9EBE254363E983F4F94517EB9585FDB112E7B1CCE11A33C5BBA23F8D5DE9D3415BA526489AC796A36FBA76D4293C8DFB673708CED10C9732EEC472D9E43D2626AA104121666E79DD8F2FF6BAC0143BD62E0EE826AF6459779C162613508D48BFE2FC8DD558A1834D7205F96EA8D446E9B371E78E990A3995B1052DCBA9CA0AF99CC77ED2A8B55B2B882BA29D4BB4B07FA91AB4D2F10FBB93732B077335A7E6D96FE813AEDC3711A85CD0C13AE22B28C14FCCE3AF4C1F5D2C0F7697DEC7487CCFC0ED4E77B1B65F39BAD5236E3D3C69D33FC484"; $hashBinaryValue = mhash(MHASH_SHA1, $encrypted_string); $hashValue = bin2hex($hashBinaryValue); echo 'hashValue='.$hashValue.'<br>'; The example hashed output should be: Code: [Select] 31f6d26b18d3c04895cdc2cc05cbd9ad003f2d3e I cannot seem to replicate this output using the available functions? I've tried the following: Code: [Select] $hashBinaryValue = hash('sha1', $encrypted_string); $hashValue = bin2hex($hashBinaryValue); And also: Code: [Select] $hashBinaryValue = sha1($encrypted_string); $hashValue = bin2hex($hashBinaryValue); Both generate: Code: [Select] 37333736363862393037313732326265346438396433633236383936363430376434613665363231 I've found a webpage that can generate the SHA1 hash, but do not know what language they've done it in. http://www.fileformat.info/tool/hash.htm?hex=B0436CBFBC5CAAFB7339AF4A1DF845974D53B9D369146E2E4F1451929D9EBE254363E983F4F94517EB9585FDB112E7B1CCE11A33C5BBA23F8D5DE9D3415BA526489AC796A36FBA76D4293C8DFB673708CED10C9732EEC472D9E43D2626AA104121666E79DD8F2FF6BAC0143BD62E0EE826AF6459779C162613508D48BFE2FC8DD558A1834D7205F96EA8D446E9B371E78E990A3995B1052DCBA9CA0AF99CC77ED2A8B55B2B882BA29D4BB4B07FA91AB4D2F10FBB93732B077335A7E6D96FE813AEDC3711A85CD0C13AE22B28C14FCCE3AF4C1F5D2C0F7697DEC7487CCFC0ED4E77B1B65F39BAD5236E3D3C69D33FC484 Any help or input would be greatly appreciated =) Hi guys, Iv been reading into password salting and im struggling to understand its purpose. From what iv read you can basic salt a password by doing the following: $salt = "randomtext"; $password = "apple"; $password = md5($password.$salt); I was wondering though, if a hacker is able to crack the md5, wont they see the password and the salt? Example: a hacker cracks the md5 to reveal applerandomtext. From applerandomtext it wont be hard for them to work out that the password is apple. So doesn't that make the idea of salting pointless? Salting passwords... How can you update the salting without getting all the users to change their password? Is the salting set in stone once created? I was wondering how most people use salt or what is the order of the steps to use salt? Does the script take the new password then encrypt it then add salt and in encrypt it again, are they just added together and then encrypted or is it a combination of something like that? And I guess the de-encrypting would be the reverse. Not looking for code just the big picture. Thanks S |