`
天梯梦
  • 浏览: 13638482 次
  • 性别: Icon_minigender_2
  • 来自: 洛杉矶
社区版块
存档分类
最新评论

PHP 加密用户密码 How to store passwords safely with PHP and MySQL

 
阅读更多
  1. Do not store password as plain text
  2. Do not try to invent your own password security
  3. Do not ‘encrypt’ passwords
  4. Do not use MD5
  5. Do not use a single site-wide salt
  6. What you should do
  • Use a cryptographically strong hashing function like bcrypt (see PHP's crypt() function).
  • Use a random salt for each password.
  • Use a slow hashing algorithm to make brute force attacks practically impossible.
  • For bonus points, regenerate the hash every time a users logs in.
$username = 'Admin';
$password = 'gf45_gdf#4hg';

// A higher "cost" is more secure but consumes more processing power
$cost = 10;

// Create a random salt
$salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.');

// Prefix information about the hash so PHP knows how to verify it later.
// "$2a$" Means we're using the Blowfish algorithm. The following two digits are the cost parameter.
$salt = sprintf("$2a$%02d$", $cost) . $salt;

// Value:
// $2a$10$eImiTXuWVxfM37uY4JANjQ==

// Hash the password with the salt
$hash = crypt($password, $salt);

// Value:
// $2a$10$eImiTXuWVxfM37uY4JANjOL.oTxqp7WylW7FCzx2Lc7VLmdJIddZq

 

In the above example we turned a reasonably strong password into a hash that we can safely store in a database. The next time the user logs in we can validate the password as follows:

$username = 'Admin';
$password = 'gf45_gdf#4hg';

// For brevity, code to establish a database connection has been left out

$sth = $dbh->prepare('
  SELECT
    hash
  FROM users
  WHERE
    username = :username
  LIMIT 1
  ');

$sth->bindParam(':username', $username);

$sth->execute();

$user = $sth->fetch(PDO::FETCH_OBJ);

// Hashing the password with its hash as the salt returns the same hash
if ( hash_equals($user->hash, crypt($password, $user->hash)) ) {
  // Ok!
}

 

A few additional tips to prevent user accounts from being hacked:

  • Limit the number of failed login attempts.
  • Require strong passwords.
  • Do not limit passwords to a certain length (remember, you're only storing a hash so length doesn't matter).
  • Allow special characters in passwords, there is no reason not to.

注意:hash_equals (PHP 5 >= 5.6.0) 如果你的php版本 phpversion()不够,可以尝试使用下面的代码

原文:https://alias.io/2010/01/store-passwords-safely-with-php-and-mysql/

 

password_compat

 This library requires PHP >= 5.3.7 OR a version that has the $2y fix backported into it (such as RedHat provides). Note that Debian's 5.3.3 version is NOT supported.

使用前,用下面代码测试当前域名是否可以用这个password_compat

<?php
require "lib/password.php";
echo "Test for functionality of compat library: " . (PasswordCompatbinarycheck() ? "Pass" : "Fail");
echo "n";

 

Usage

Creating Password Hashes

To create a password hash from a password, simply use the password_hash function.

$hash = password_hash($password, PASSWORD_BCRYPT);

 

Note that the algorithm that we chose is PASSWORD_BCRYPT. That's the current strongest algorithm supported. This is the BCRYPT crypt algorithm. It produces a 60 character hash as the result.

 

BCRYPT also allows for you to define a cost parameter in the options array. This allows for you to change the CPU cost of the algorithm:

$hash = password_hash($password, PASSWORD_BCRYPT, array("cost" => 10));

 

That's the same as the default. The cost can range from 4 to 31. I would suggest that you use the highest cost that you can, while keeping response time reasonable (I target between 0.1 and 0.5 seconds for a hash, depending on use-case).

 

Another algorithm name is supported:

    PASSWORD_DEFAULT

This will use the strongest algorithm available to PHP at the current time. Presently, this is the same as specifying PASSWORD_BCRYPT. But in future versions of PHP, it may be updated to use a stronger algorithm if one is introduced. It can also be changed if a problem is identified with the BCRYPT algorithm. Note that if you use this option, you are strongly encouraged to store it in a VARCHAR(255) column to avoid truncation issues if a future algorithm increases the length of the generated hash.

 

It is very important that you should check the return value of password_hash prior to storing it, because a false may be returned if it encountered an error.

 

Verifying Password Hashes

To verify a hash created by password_hash, simply call:

    if (password_verify($password, $hash)) {
        /* Valid */
    } else {
        /* Invalid */
    }

 

That's all there is to it.

 

Rehashing Passwords

From time to time you may update your hashing parameters (algorithm, cost, etc). So a function to determine if rehashing is necessary is available:

    if (password_verify($password, $hash)) {
        if (password_needs_rehash($hash, $algorithm, $options)) {
            $hash = password_hash($password, $algorithm, $options);
            /* Store new hash in db */
        }
    }

 

 

项目地址:https://github.com/ircmaxell/password_compat

下载:password_compat-master

 

转自:PHP 加密用户密码 How to store passwords safely with PHP and MySQL

 

 

分享到:
评论

相关推荐

    used to set up passwords, and data structure of the stack to achieve.

    -The algorithm is used to set up passwords, and data structure of the stack to achieve.这个算法,是用来设置密码的,有数据结构中的栈来实现的。-The algorithm is used to set up passwords, and data ...

    mysql-8-cookbook2018

    RDBMS and how to use MySQL for transactions. Chapter 6, Binary Logging, demonstrates how to enable binary logging, various formats of binary logs, and how to retrieve data from binary logs. Chapter 7,...

    pam_mysql_0.7RC1

    PAM-MySQL is licensed under GNU Public License and I heard that GPL requires the program that links to a GPL'ed shared binary object at runtime also being covered by GPL. Is it safe to use PAM-MYSQL ...

    php.ini-development

    Expressions in the INI file are limited to bitwise operators and parentheses: ; | bitwise OR ; ^ bitwise XOR ; & bitwise AND ; ~ bitwise NOT ; ! boolean NOT ; Boolean flags can be turned on using ...

    Wicked.Cool.PHP

    So you'll learn how to encrypt your confidential data, safeguard your passwords, and prevent common cross-site-scripting attacks. And you'll learn how to customize all of the scripts to fit your own ...

    KeePass A lightweight and easy-to-use password manager Windows

    With so many passwords to remember and the need to vary passwords to protect your valuable data, it’s nice to have KeePass to manage your passwords in a secure way. KeePass puts all your passwords ...

    [自由软件]CHINAPGP一次密码加密程序 JCC

    JCC是ChinaPGP最新的一次密码(OTP,one time passwords)体制文件加密工具.该工具主要用于文件的保密传送. 在进行通信前,首先使用SecureRandom随机数生成器生成一个Key文件,key文件大小由用户A自行设定, key文件一旦...

    Programming Excel With Vba And .net.chm

    Programming Excel with VBA and .NET Preface Part I: Learning VBA Chapter 1. Becoming an Excel Programmer Section 1.1. Why Program? Section 1.2. Record and Read Code Section 1.3. Change ...

    Securing PHP Web Applications.pdf

    How to Sanitize Data to Prevent Buffer Overflows 48 Patch the Application 49 Verify That We’re Running the Latest Stable Versions 49 Check Variable Sanitation 51 Wrapping It Up 52 Chapter 5 Input ...

    使用MD5算法对密码进行加密

    使用MD5算法对密码进行加密 Using the MD5 algorithm to encrypt passwords

    How Software Works

    How Software Works breaks down these processes with patient explanations and intuitive diagrams so that anyone can understand—no technical background is required, and you won’t be reading through ...

    Building.Secure.PHP.Apps

    Do you ever wonder how vulnerable you are to being hacked? Do you feel confident about storing your users sensitive information? Imagine feeling confident in the integrity of your software when you ...

    Attacking Network Protocols

    You'll learn how to: Capture, manipulate, and spoof packets both passively and on the wire Create your own capture framework Reverse engineer code, brute force passwords, and decrypt traffic ...

    无线密码查看工具(SterJo Wireless Passwords) 1.4 中文汉化版

    无线密码查看工具(SterJo Wireless Passwords) 1.4 中文汉化版

    PHPershou.zip

    And it supports a wide range of database connections, with a lot of extensions, security is also very high performance, easy to learn and use.  This paper introduces the feasibility of the system ...

    React Quickly: Painless web apps with React, JSX, Redux, and GraphQL

    Chapter 19: Project: Checking passwords with Jest Chapter 20: Project: Implementing autocomplete with Jest, Express, and MongoDB Appendix A: Installing applications used in this book Appendix B: ...

    Active Directory Cookbook, 3rd Edition.pdf

    Covers how to trigger and disable the Knowledge Consistency Checker (KCC), how to query metadata, force replication, and determine what changes have yet to replicate between domain controllers. ...

    BlackBerry For Dummies 第三版

    Packed with information to help you make the most of this amazing device, BlackBerry For Dummies explains how to send and receive e-mail and instant messages, surf the Web, take photos, make phone ...

    OFFICE文档遗失密码处理

    OFFICE文档遗失密码处理 Office Password Recovery Toolbox, version 1.0. Copyright (C) 2003-2007 Rixler Software. All Rights Reserved. http://www.rixler.com Overview ======== Office Password Recovery ...

Global site tag (gtag.js) - Google Analytics