PHP - Sha1 Hashing Goes Wrong
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 Similar TutorialsHi 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 =) Is this okay to do for dealing with passwords before running an insert query into a database? $password = sha1(mysqli_real_escape_string($dbc, $_POST['password'])); Is there anything wrong in doing this? I currently have 100,000+ users all with their passwords hashed in md5(). I want to secure it a bit by simply hashing all of their existing hashes to sha1() and then check their password matches the sha1(md5()). Is there any reason why I shouldn't do this? Hi, So basically this is error: Code: [Select] if (strcmp($extuser,$username) == 0 && strcmp($extpass,$password) == 0) extpass is a value it reads from the database. That value is sha1-hashed. Password is plain and is sent via a form. So what happens is the following: extuser and username equals 0, as they match. extpass and password matches IF i put the sha1 hashed password as the password. So no problems in that, it's supposed to work that way. If we change the code a bit, so that the user shouldn't post an unknown password: Code: [Select] if (strcmp($extuser,$username) == 0 && strcmp($extpass,sha1($password)) == 0) Right, so we take the submitted password and sha1 it. Then check if that new string matches the database and whops, login failed. Okay.. by doing some debugging by printing the actual values i conclude this: The sha1($password) equals 139a8cf8be8..... while in my database all the letters are CaSe. This is most likely the error.. Any ideas for a fix? I have the following array which builds a concatenation of the items in tree-like form. $arrayT = array(); $arrayT[0] = "a"; $arrayT[1] = "b"; $arrayT[2] = "c"; $arrayT[3] = "d"; $arrayT[4] = "e"; $arrayT[5] = "f"; $arrayT[6] = "g"; $arrayT[7] = "h"; $arrayT = buildTree($arrayT); print_r($arrayT); function buildTree($array) { $arrayTree = $array; $start = 0; $end = count($arrayTree); $i = 0; while ($start != $end - 1) { if ($i % 2 == 1) { $arrayTree[count($arrayTree) - 1].=$arrayTree[$start + $i]; } else $arrayTree[] .= $arrayTree[$start + $i]; $i++; if (($start + $i) == $end) { $i = 0; $start = $end; $end = count($arrayTree); } } return $arrayTree; } Example output is Quote Array ( => a [1] => b [2] => c [3] => d [4] => e [5] => f [6] => g [7] => h [8] => ab [9] => cd [10] => ef [11] => gh [12] => abcd [13] => efgh [14] => abcdefgh ) I would like the values to be hashed using sha1. e.g value at [8] ab would be the hash of a and [1] b, value [12]abcd would be the hash of the values at [8]ab and [9]cd. I modified it myself in the next code snippet but I still don't feel it's doing what it's meant function buildTree($array) { $arrayTree = $array; $start = 0; $end = count($arrayTree); $i = 0; while ($start != $end - 1) { if ($i % 2 == 1) { $arrayTree[count($arrayTree) - 1].=$arrayTree[$start + $i]; sha1($arrayTree[count($arrayTree)-1].=$arrayTree[$start + $i]); } else $arrayTree[] .= sha1($arrayTree[$start + $i]); $i++; if (($start + $i) == $end) { $i = 0; $start = $end; $end = count($arrayTree); } } return $arrayTree; } $val1 = sha1($arrayT[0]); $val2 = sha1($arrayT[1]); $val3 = sha1($val1.$val2); $val4 = sha1("ab"); echo "VAL1 ".$val1; echo "<br/>"; echo "VAL2 ".$val2; echo "<br/>"; echo "VAL3 ".$val3; echo "<br/>"; echo "VAL4 ".$val4; Anyone any ideas? Thankyou. 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. Php Lovers,
When you register on my site, you supposed to get an account activation link emailed to confirm your email and account opening. Activation Link contains activation code. Code, I wanted all numbers like so: 193736262829292 And not alphanumerical like so: djkqh3kl3lwnj3j22b Someone did this line for me 1.5yrs back and only just came to my attention it is generating alphanumeric chars as I was checking the column where it would save the code to see if the column type is correct or not. Type was varchar all this time. If the code becomes only numerical then can switch column (account_activation_code) type to "INT".
$account_activation_code = sha1( (string) mt_rand(0,99999999)); //Type Casted the INT to STRING on the 11st parameter of sha1 as it needs to be a string.
Another programmer did that line 1.5yrs back. Lost contact with him. Tell me, why sha1 needs to be TypeCasted to "STRING" ? As far as I remember 1.5yrs back it had to be converted to STRING. Else, was giving error. I mean, we dealing with INT here "mt_rand(0,99999999)" so why php force us to TypeCast to STRING here ? Absurd! Right ? Context:
<?php //Required PHP Files. include 'configurations_site.php'; //Required on all webpages of the site. Must include here too. Else, conn.php data would not be found. conn.php residing in site_configurations.php. include 'header_site.php'; //Step 1: Before registering user Account, check if User is already registered or not. Else, check if User is registering through invitation or not. //Check if User is already logged-in or not. Get the login_check() custom FUNCTION to check. if (login_check() === TRUE) { die("You are already logged-in! No need to register again!"); } //Check if the Url contains a Sponsor Username or not. If not, then barr the registration. if (isset($_GET['sponsor_username']) && !empty($_GET['sponsor_username'])) { $sponsor_username = $_GET["sponsor_username"]; } else { die("Signups only through invitations only!<br> Therefore, you need to be invited by a registered member who knows you personally!"); } if ($_SERVER['REQUEST_METHOD'] == "POST") { //Step 2: Check User submitted details. //Check if User made all the required inputs or not. if (isset($_POST["fb_tos_agreement_reply"]) || isset($_POST["username"]) && isset($_POST["password"]) && isset($_POST["password_confirmation"]) && isset($_POST["fb_tos"]) && isset($_POST["primary_domain"]) && isset($_POST["primary_domain_confirmation"]) && isset($_POST["primary_website_email"]) && isset($_POST["primary_website_email_confirmation"]) && isset($_POST["age_range"])) { //Step 3: Check User details for matches against database. If no matches then validate inputs to register User Account. //Create Variables based on user inputs. $fb_tos_agreement_reply = trim($_POST["fb_tos_agreement_reply"]); $username = filter_var(trim($_POST["username"],FILTER_SANITIZE_STRING)); $password = $_POST["password"]; $password_confirmation = $_POST["password_confirmation"]; $primary_website_domain = filter_var(trim($_POST["primary_website_domain"],FILTER_SANITIZE_DOMAIN)); $primary_website_domain_confirmation = filter_var(trim($_POST["primary_website_domain_confirmation"],FILTER_SANITIZE_DOMAIN)); $primary_website_email = filter_var(trim($_POST["primary_website_email"],FILTER_SANITIZE_EMAIL)); $primary_website_email_confirmation = filter_var(trim($_POST["primary_website_email_confirmation"],FILTER_SANITIZE_EMAIL)); $primary_website_email_extracted_domain = substr(strrchr($primary_website_email,"@"),1); $age_range = filter_var(trim($_POST["age_range"],FILTER_SANITIZE_STRING)); $account_activation_code = sha1( (string) mt_rand(0,99999999)); //Type Casted the INT to STRING on the 11st parameter of sha1 as it needs to be a string. $account_activation_link = sprintf("http://www.%s/%s/activate_account.php?website_email=%s@account_activation_code=%s", $site_domain,$social_network_name,urlencode("$primary_website_email"),urlencode($account_activation_code)); $account_activation_status = 0; //1 = active; 0 = inactive. $hashed_password = password_hash($password,PASSWORD_DEFAULT); //Encrypt the password. if (strlen($fb_tos_agreement_reply) < 1 || $fb_tos_agreement_reply != "Yes") { echo "You must agree to our <a href='tos.html'>Terms & Conditions</a>!"; //Check if inputted Username is valid or not. } elseif (!filter_var($username,FILTER_VALIDATE_STRING)) { echo "You entered an Invalid Username!"; //Check if inputted Username is between the required 8 to 30 characters long or not. } elseif (strlen($username) < 8 || strlen($username) > 30) { echo "Username has to be between 8 to 30 characters long!"; //Check if Password is between 8 to 30 characters long or not. } elseif (strlen($password) < 8 || strlen($password) > 30) { echo "Password must be between 8 to 30 characters long!"; //Check if both inputted Passwords match or not. } elseif ($password != $password_confirmation) { echo "Your entered 2 Passwords don't match!"; //Check if both inputted Domains match or not. } elseif ($primary_website_domain != $primary_website_domain_confirmation) { echo "Your entered 2 Primary Website Domains don't match!"; //Check if inputted Domain is valid or not. } elseif (!filter_var($primary_website_domain,FILTER_VALIDATE_DOMAIN)) { echo "You entered an Invalid Domain Name!"; //Check if both Email Inputs match or not. } elseif ($primary_website_email != $primary_website_email_confirmation) { echo "Your 2 Email inputs don't match!"; //Check if inputted Email is valid or not. } elseif (!filter_var($primary_website_email,FILTER_VALIDATE_EMAIL)) { echo "You entered an Invalid Email Address!"; //Check if inputted Domain and Email Domain match or not. } elseif ($primary_website_email_extracted_domain != $primary_website_domain) { echo "Your Email Address must belong to your Domain Name: \"$primary_website_domain\"!"; } else { //Select Username and Email to check against Mysql DB if they are already regsitered or not. $stmt = mysqli_prepare($conn,"SELECT username,primary_domain,primary_website_email FROM users WHERE username = ? OR primary_domain = ? OR primary_website_email = ?"); mysqli_stmt_bind_param($stmt,'sss',$username,$primary_website_domain,$primary_website_email); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); $row = mysqli_fetch_array($result, MYSQLI_ASSOC); //Check if inputted Username is already registered or not. if ($row['username'] == $username) { echo "That Username is already registered!"; //Check if inputted Domain is already registered or not. } elseif ($row['primary_domain'] == $primary_website_domain) { echo "That Domain Name is already registered!"; //Check if inputted Email is already registered or not. } elseif ($row['primary_website_email'] == $primary_website_email) { echo "That Email Address is already registered!"; } else { //Insert the User's inputs into Mysql database using Php's Sql Injection Prevention Method "Prepared Statements". $stmt = mysqli_prepare($conn,"INSERT INTO users(account_activation_code,account_activation_status,id_video_verification_status,sponsor_username,recruits_number,username,password,primary_domain,primary_website_email,age_range,registering_country,registering_ip,registering_browser,registering_os,registering_isp) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); mysqli_stmt_bind_param($stmt,'siisissssssssss',$account_activation_code,$account_activation_status,$id_video_verification_status,$sponsor_username,$recruits_number,$username,$hashed_password,$primary_website_domain,$primary_website_email,$age_range,$registering_country,$registering_ip,$registering_browser,$registering_os,$registering_isp); mysqli_stmt_execute($stmt); //Check if User's registration data was successfully submitted or not. if (!$stmt) { echo "Sorry! Our system is currently experiencing a problem registering your account! You may try registering some other time!"; exit(); } else { //Email the Account Activation Link for the User to click it to confirm their email and activate their new account. $to = "$primary_website_email"; $subject = "Your ".$site_name." Account Activation Details"; $body = nl2br(" ===============================\r\n ".$site_name." \r\n ===============================\r\n From: ".$site_admin_email."\r\n To: ".$primary_website_email."\r\n Subject: Your ".$subject."\r\n Message: ".$username."\r\n You need to click on this following <a href=".$account_activation_link.">link</a> to activate your account.\r\n "); $headers = "From: ".$site_admin_email."\r\n"; if (!mail($to,$subject,$body,$headers)) { echo "Sorry! We have failed to email you your Account Activation details. Please contact the website administrator!"; exit(); } else { echo "<h3 style='text-align:center'>Thank you for your registration!<br /> Check your email $website_email for details on how to activate your account which you just registered.<h3>"; exit(); } } } } } } ?> <!DOCTYPE html> <html> <head> <title><?php echo "$social_network_name";?> Signup Page</title> </head> <body> <div class ="container"> <?php //Error Messages. if (isset($_SESSION['error']) && !empty($_SESSION['error'])) { echo '<p style="color:red;">'.$_SESSION['error'].'</p>'; } ?> <?php //Session Messages. if (isset($_SESSION['message']) && !empty($_SESSION['message'])) { echo '<p style="color:red;">'.$_SESSION['error'].'</p>'; } ?> <?php //Clear Registration Session. function clear_registration_session() { //Clear the User Form inputs, Session Messages and Session Errors so they can no longer be used. unset($_SESSION['message']); unset($_SESSION['error']); unset($_POST); exit(); } ?> <h2><p align="center"><?php echo "$site_name Member Sign Up Form";?></p></h2> <form name "registration_form" method = "post" action="" enctype = "multipart/form-data"> <div class="form-group"> <p align="left"><label>Username:</label> <input type="text" placeholder="Enter a unique Username" name="username" required [A-Za-z0-9] autocorrect=off value="<?php if(isset($_POST['username'])) { echo htmlentities($_POST['username']); }?>"> </p> </div> <div class="form-group"> <p align="left"><label>Password:</label> <input type="password" placeholder="Enter a new Password" name="password" required [A-Za-z0-9] autocorrect=off> </p> </div> <div class="form-group"> <p align="left"><label>Repeat Password:</label> <input type="password" placeholder="Repeat Password" name="password_confirmation" required [A-Za-z0-9] autocorrect=off> </p> </div> <div class="form-group"> <p align="left"><label>Primary Domain:</label> <input type="text" placeholder="Enter your Primary Domain" name="primary_website_domain" required [A-Za-z0-9] autocorrect=off value="<?php if(isset($_POST['primary_website_domain'])) { echo htmlentities($_POST['primary_website_domain']); }?>"> </p> </div> <div class="form-group"> <p align="left"><label>Repeat Primary Domain:</label> <input type="text" placeholder="Repeat Primary Domain" name="primary_website_domain_confirmation" required [A-Za-z0-9] autocorrect=off value="<?php if(isset($_POST['primary_website_domain_confirmation'])) { echo htmlentities($_POST['primary_website_domain_confirmation']); }?>"> </p> </div> <div class="form-group"> <p align="left"><label>Primary Website Email:</label> <input type="text" placeholder="Primary Website Email" name="primary_website_email" required [A-Za-z0-9] autocorrect=off value="<?php if(isset($_POST['primary_website_email'])) { echo htmlentities($_POST['primary_website_email']); }?>"> </p> </div> <div class="form-group"> <p align="left"><label>Repeat Primary Website Email:</label> <input type="text" placeholder="Repeat Website Email" name="primary_website_email_confirmation" required [A-Za-z0-9] autocorrect=off value="<?php if(isset($_POST['primary_website_email_confirmation'])) { echo htmlentities($_POST['primary_website_email_confirmation']); }?>"> </p> </div> <div class="form-group"> <p align="left"><label>Age Range:</label> <input type="radio" name="age_range" value="18-20" <?php if(isset($_POST['age_range'])) { echo 'checked'; }?> required>18-20 <input type="radio" name="age_range" value="21-25" <?php if(isset($_POST['age_range'])) { echo 'checked'; }?> required>21-25 <input type="radio" name="age_range" value="26-30" <?php if(isset($_POST['age_range'])) { echo 'checked'; }?> required>26-30 <input type="radio" name="age_range" value="31-35" <?php if(isset($_POST['age_range'])) { echo 'checked'; }?> required>31-35 <input type="radio" name="age_range" value="36-40" <?php if(isset($_POST['age_range'])) { echo 'checked'; }?> required>36-40 <input type="radio" name="age_range" value="41-45" <?php if(isset($_POST['age_range'])) { echo 'checked'; }?> required>41-45 <input type="radio" name="age_range" value="46-50" <?php if(isset($_POST['age_range'])) { echo 'checked'; }?> required>46-50 <input type="radio" name="age_range" value="51-55" <?php if(isset($_POST['age_range'])) { echo 'checked'; }?> required>51-55 <input type="radio" name="age_range" value="56-60" <?php if(isset($_POST['age_range'])) { echo 'checked'; }?> required>56-60 <input type="radio" name="age_range" value="61-65" <?php if(isset($_POST['age_range'])) { echo 'checked'; }?> required>61-65 <input type="radio" name="age_range" value="66-70" <?php if(isset($_POST['age_range'])) { echo 'checked'; }?> required>66-70 <input type="radio" name="age_range" value="71-75" <?php if(isset($_POST['age_range'])) { echo 'checked'; }?> required>71-75 </p> </div> <div class="form-group"> <p align="left"><label>Agree To Our Terms & Conditions ? :</label> <input type="radio" name="fb_tos_agreement_reply" value="Yes" <?php if(isset($_POST['fb_tos_agreement_reply'])) { echo 'checked'; }?> required>Yes <input type="radio" name="fb_tos_agreement_reply" value="No" <?php if(isset($_POST['fb_tos_agreement_reply'])) { echo 'checked'; }?> required>No </p> </div> <p align="left"><input type="submit" class="btn btn-default" name="submit" value="Submit"></p> <p align="left"><input type="reset" class="btn btn-default" name="reset" value="Reset"></p> <p align="left"><font color="red" size="3"><b>Already have an account ?</b><a href="login.php">Login here!</a></font></p> </form> </div> </body> </html>
I am still experimenting with SANITIZATION and so ignore the SANITIZATION lines.
I am reworking some code from a password authentication I did a long long time ago. The original code is using SHA1() function to encrypt the passwords for storage in the MySQL database. Is that still considered the way to go, or should I be using a different method for encrypting the little buggers? Thanks 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.
{ 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 ? I 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. 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?
What is the latest and greatest way to hash data in PHP? 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. Hi guys I have a script which i've been playing around with thanks to Spiderwell: http://www.phpfreaks.com/forums/index.php?action=profile;u=35078 I have sort of merged it with another 'member managment' script which is working great. Now i can't seem to correctly create a login page to pass the hashed password using (sha1). Now all i want to do is verify the username and the (hashed) password according to the database and allow the user in. The script i am using to check login works fine without a hashed password in the database. But ideally i'd like to use a hashed form of password. Can somebody show me what change i need to make in this script below in order to pass a sha1 hashed password? I'm guessing it's a really small change from the examples i've seen online, but i just cant seem to get mine to work. :| Your help would be much appreciated. Login Page PHP: Code: [Select] <form name="login" method="post" action="check_login.php3"> <p><strong>Secured Area User Log-in</strong></p> <p>Username: <input name="bioname" type="text" id="bioname"></p> <p>Password: <input name="biopass" type="password" id="biopass"></p> <p> </p> <p><input type="submit" name="Submit" value="Login"></p> </form> Check Login Processor (which is the file i that needs the sha1 added somewhere i think) Code: [Select] <?php require_once('config.php3'); // Connect to the server and select the database. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db")or die("Unable to select database"); // $loginusername = false; $loginpassword = false; $err = false; // default error message is empty // The username and password sent from login.php //the isset() basically means if its there get it, otherwise dont bother if (isset($_POST['bioname'])) $loginusername=$_POST['bioname']; if (isset($_POST['biopass']))$loginpassword=$_POST['biopass']; // if either isnt filled in, tell the user, a very basic bit of validation if (!$loginusername || !$loginpassword) $err = "please complete the form"; if (!$err) //if no error continue { //The following bit of coding protects from MySQL injection attacks $loginusername = stripslashes($loginusername); $loginpassword = stripslashes($loginpassword); $loginusername = mysql_real_escape_string($loginusername); $loginpassword = mysql_real_escape_string($loginpassword); //you could add other things like check for text only blah blah $sql="SELECT * FROM $tbl WHERE bioname='$loginusername' and biopass='$loginpassword'"; $result=mysql_query($sql); // Count how many results were pulled from the table $count=mysql_num_rows($result); // If the result equals 1, continue if($count==1) { session_start(); $_SESSION['user'] = $loginusername; // store session data //please see I have used a session variable that is generic not specific, otherwise you will have to make this page different for every user //that would be a pain in the ass, you don't need to have user1 or user2, its the value stored that relevant, not what the variable name is header("Location: {$loginusername}/index.php3"); } else { $err = "Wrong Username or Password"; } }// end login if statement if ($err) // show error message if there is one { echo $err; echo "<br>Please go back in your browser and try again"; } ?> The secure page: Code: [Select] <?php session_start(); $mypath = $_SERVER["REQUEST_URI"]; //echo $mypath; // for debugging //now we have the path lets see if the username is in that path, i.e. test2 is inside /something/test2/index.php //use the built in strpos() function, which returns position of the last occurance of the string you are looking for inside another string. //http://php.net/manual/en/function.strrpos.php if(strpos($mypath,"/".$_SESSION['user']."/"))//on testing it failed initially as username test is found in path /test2/ so i added the slashes to stop that. so /test/ doesnt get found in /test2/ { echo "congratulations you are the right person in the right place"; } else { session_destroy(); //kill the session, naughty person trying to come here header("Location: ../login.php3"); die();// stop page executing any further } ?> <html> <body> </body> </html> Thanks and i look forward to your replies. 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. Hi, I'm trying to add encryption to a signup for a college assignment, but find that after adding the sha1 and salt encryption the code does not work. The code worked before adding the encryption. Since adding the encryption I've also adding the corresponding fields for username and password into the sql database and double checked, and triple checked all the php, html form and MySQL tables and fields, but don't see any thing wrong. Can anybody else see any immediate problems with the code snippet below? If so, can you please let me know? session_start(); $salt = 'The sky is blue and all the trees are green'; $data = array_map('mysql_escape_string', $_POST); $password = sha1($data['password'].$salt); $query = " INSERT INTO customers ( first_name, last_name, address, mobile, email, username, password ) VALUES ( '{$data['first_name']}', '{$data['last_name']}', '{$data['address']}', '{$data['mobile']}', '{$data['email']}' '{$data['username']}', '$password' ) "; if(mysql_query($query)) { echo 'Your login details have been saved.'; } else { echo 'Your login details have not been saved.<br>'; echo 'Please try again later.'; } Thanks. 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! 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)?
<?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. |