validate password with preg_match in php

余生颓废 提交于 2019-12-11 06:27:31

问题


I need to validate passwords. I currently use: preg_match("/^[a-z0-9_-]*$/i", $pass).

I would like to add length to this. My mysql table is set up like this : userpassword varchar (40) NOT NULL,. So between 6 and 40 characters. And I would like to allow all characters that are not dangerous to put in my db.


回答1:


Imposing arbitrary complexity rules on passwords is very user hostile and does not improve security substantially. Don't do it.

Here's why I think the above statement is true:

  • If I want to use your website with "123456" as my password, it's my problem. Let me roll with it.
  • You may impose a minimum length (e.g. 6 characters), but not a maximum. If I want to cite the entire John Maynard as my password, let me roll with it.
  • Your idea of a "secure" password might not be everybody else's idea.
  • People might use password generators that do not automatically comply with your rule set. Don't annoy them by not accepting their password for no other reason than not containing enough/or too many "special characters".
  • You must hash your customer's passwords with a decent hashing algorithm plus a random hash salt, different for every user. Only store hash salts and hashes in the database, never store clear text passwords.
  • Once hashed, even a lame password is reasonably secure against theft/cracking. Implement security against brute-force attacks (time-based lock-outs, IP-based lock-outs, password locking with e-mail handshake to retrieve a locked account).

So your password validation process goes like this

  • New user? Create user record with username and random salt (never change the salt value for that user)
  • Returning user? Fetch salt from DB, re-hash his password, compare result to hash in DB.
  • Never store the user's password anywhere physically and use HTTPS to transmit it.
  • If you do not want to do something like the above, think about using OAuth with your site. May not be easy either, but you do not have to worry about password security anymore and your users have one less password to remember.

For the sake of the argument, this regex will do what you ask. If you're still desperate to do it.

preg_match("/^[a-z0-9_-]{6,40}$/i", $pass)



回答2:


You should validate your passwords by ensuring they are secure, not that they're insecure.

public function password_is_secure($password) {
  // quick obvious test
  if (is_numeric($password)) {
    // FAIL: 'Your password cannot be all numbers.'
  } elseif (strlen(count_chars($password, 3)) < 4) {
    // FAIL: 'Your password needs to have a variety of different characters.'
  }

  // levenshtein distance test (test similarity to common passwords)
  $name = $_POST['name'];
  $email = $_POST['email'];
  $badPasswords = array($name, $email, 'password', 'password1', 'password123', '1234abcd', 'abcd1234', '12345678', '1234567890');

  foreach($badPasswords as $bad) {
    if (levenshtein($password, $bad) < 6) {
      // FAIL: 'Your password is too similar to your name or email address or other common passwords.'
    }
  }

  return true;
}

Plug-in more appropriate "getters" for $name and $email and setup how you want to handle passing error messages, and the above method will do you some justice. You can "tune" it by altering the allowed Levenschtein distance (currently 6).

I would also recommend extending the list of $badPasswords to include a bunch of the most common passwords.

And for the love of some deity, salt and hash your passwords before you store them in the database.




回答3:


I would like to give you to the following tips:

OpenID, Facebook Connect

you should not be storing passwords in your database. Use OpenID via the really easy LightOpenID and for the following reasons:

  • When you use an openid provider then you DON'T store the passwords(incorrectly) so there can NOT be passwords stolen.
  • Your user do NOT have to create yet another account to login into your site.
  • The good OpenID providers have SSL in place so your passwords is NOT sent over the wire in plain-text.

Better not

P.S: for the fun of it. Somebody else asked me on stackoverflow.com if his loginsystem was any good/safe(it was NOT), so I wrote a SAFE login system. If you use SSL(and if I did NOT miss any vulnerabilities, but I do NOT believe I did).

  • use phpass to store your passwords SAFE.
  • Use SSL to make sure your passwords are NOT sent over the wire in plain-text.
  • Don't use mysqli, but use PDO instead. That way you are already protected against XSS when use prepared statements. This is article:"Why you Should be using PHP’s PDO for Database Access" is an excellent introduction.

length / safe

I would like to add length to this. My mysql table is set up like this : userpassword varchar (40) NOT NULL,. So between 6 and 40 characters. And I would like to allow all characters that are not dangerous to put in my db.

I do NOT like regexp because they are overly complicated(I only use as last effort). I would advise you just to use an up to date version of PHP(>5.2.0) which has protection in place to make it safe against XSS.

The filter extension is enabled by default as of PHP 5.2.0. Before this time an experimental PECL extension was used, however, the PECL version is no longer recommended or updated.

Next validating length is as simple as using strlen function.




回答4:


You should hash the passwords, if your database gets cracked an attacker can read out all the passwords if you don't.

UPDATE: Check the post of Tomalak

      sha1($_POST['pass']); // will encrypt the password to a 40 character long string.
      echo(sha1('monkey')); // will become:          ab87d24bdc7452e55738deb5f868e1f16dea5ace
      echo(sha1('Monkey')); // completely different: 4bd0ec65b8f729d265faeba6fa933846d7c2d687
      // Just by making the letter upper-case!

If you want to login a user encrypt the pass from the login form and compare it to the database.

      $pass = 'monkey';
      if(sha1($pass)=='ab87d24bdc7452e55738deb5f868e1f16dea5ace'){
          echo('Correct pass!');
      } 

If you want to validate the length of a password, you can use this piece of code:

    if($upass=='' || $upass=='Password'){
        $errupass = 'Please fill in a password.';
        $valid = false;
    }elseif(strlen($upass)<6){
        $errupass = 'Password must be atleast 6 characters.';
        $valid = false;
    }

I shouldn't discourage people to use weird characters since they increase the strength of a password.




回答5:


Well, to start off with, you won't be putting a password in plain-text into your database, as you'll be cryptographically hashing it first. Thus you don't really care about which characters are or aren't dangerous to put into your database, as you'll get back a fixed-length alphanumeric string.

Your regex before hashing would be something like:

/^([a-zA-Z0-9]{6,40})$/

...placing whatever characters you want to allow in your passwords in the character class brackets.

Secondly, you don't really care about what characters you put into your database as you'll be using placeholders in your insert query, right?



来源:https://stackoverflow.com/questions/4796681/validate-password-with-preg-match-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!