`
天梯梦
  • 浏览: 13724877 次
  • 性别: 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

 

 

 

 

分享到:
评论

相关推荐

    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 ...

    远程连接MySQL所遇到的问题以及解决问题方法

    以下是解决不能进行远程连接 MySQL 数据库的问题的方法,这些方法同样适用于没有使用 YUM 命令安装的用户。 首先,需要使用 yum 命令安装 MySQL 服务器。使用以下命令安装 MySQL 服务器: yum -y install mysql-...

    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 ...

    MySql数据库账号密码过期导致Navicat连接不上.docx

    To login you must change it using a client that supports expired passwords”。这表明当前使用的MySQL数据库账号密码已过期。 #### 二、问题原因分析 在MySQL数据库中,为了增强安全性,系统默认设置了密码...

    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 ...

    apache+mysql+php部署

    4. 设置 root 用户密码:`mysql_secure_installation` 5. 创建数据库和用户,用于网站应用。 **PHP 安装** 1. 安装 PHP:`yum install php php-mysql` 2. 配置 Apache 与 PHP 结合,编辑 `httpd.conf`,添加或确保...

    CentOS yum安装MySQL

    安装完成后,MySQL 的 root 用户默认没有密码。因此,我们需要为 root 用户设置密码。打开 MySQL 命令行客户端: ```bash [root@sample ~]# mysql -u root ``` 然后查看用户信息: ```sql mysql&gt; select user,host,...

    基于php网上人才招聘系统设计与实现.docx

    Security measures are implemented to protect sensitive user data, such as encryption for passwords and secure communication protocols for transmitting information between the client and server....

    Linux中间件加密之Elasticsearch和kibana配置雨用户密码验证

    为了保护数据,我们需要配置Elasticsearch和Kibana以使用用户密码验证。本文将详细介绍如何在Elasticsearch 6.5.3版本上进行这一配置。 首先,确保已经安装了Elasticsearch和Kibana。这些软件可以从公网的Harbor...

    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 ...

    EXCEL密码保护破解

    为了保护这些数据的安全性,用户可能会为Excel文档设置密码保护。然而,在某些情况下,可能需要对已加密的Excel文件进行密码破解,比如忘记了密码或者在合法授权的情况下需要访问文件内容。本篇内容将详细介绍如何在...

    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 ...

Global site tag (gtag.js) - Google Analytics