How to store the password of the account in the database safely? ——Password Hash

When I was in college at the earliest, I only knew that MD5 was used to store the password of the user's account, but in fact it was very insecure, and the hash function used, digging deeper, also found it was not simple ...

One, ordinary Hash function


I won't go into details about what the hash (hash) function is.

1. Not recommended

RC4, MD4, MD5, SHA-0, SHA-1, DES, 2DES etc.

2. Recommended

SHA-2 (SHA-256, SHA-384, SHA-512), SHA-3, Blake2, etc.

The National Institute of Standards and Technology (NIST) announced that it will gradually disqualify SHA-1 as a secure hash algorithm after 2010, replacing it with its more powerful mutation algorithms: SHA-224, SHA-256, SHA-384 and SHA-512. Regardless of whether you follow the NIST standard, it is always good to use at least the SHA-256 algorithm to encrypt passwords.

Second, the strategy to deal with ordinary hash is easy to crack


Just like the mutual enhancement of attack and spear, even if the hash function is used above SHA-3, there is still the risk of being easily cracked. So we have other additional ways to solve this problem.

1. Add salt

Adding salt is to stitch another field (salt) before hashing the target field.

Note: It is more common before the salt value is added to the field.

Adding salt is effective for preventing rainbow watches.

important point:

  • Salt should not be too short
  • Salt cannot be reused (otherwise if it is cracked, everything will suffer)
  • Salt changes randomly (for example, although the user name is not repeated, the user name cannot be used as salt)

The essence of salt is to be 无差别攻击transformed into 针对性攻击.

1.1 [Expansion] Another approach to salt-HMAC

HMAC(Keyed-Hashing for Message Authentication) is actually a special kind of salting, but this salt is replaced with a more secure key .

For a detailed introduction, please see my previous article: "Cracking another website's anti-climbing mechanism & HMAC algorithm"

2. Slow hashing

High-end graphics cards (GPUs) and custom hardware can perform billions of hash calculations per second, so this type of attack can still be very efficient. In order to reduce the efficiency of the attacker, we can use slow hashing, that is, iteratively perform many hash operations .

How many times is it safe to iterate ? Suggestion from NIST official:

  • In September 2000, it is recommended to iterate a thousand times
  • 2015-2018, it is recommended to iterate 10,000 times
  • In June 2017, it is recommended to iterate 100,000 times

Three, password hash function (Password Hash)


密码哈希函数(Password Hash)It can be used to deal with the problem that ordinary hashes are easy to crack (the two strategies mentioned above are also used).

The order listed below is in chronological order, and the degree of safety and recommendation index also increase gradually.

1 、 PBKDF2

Older, few people use it, slightly.

2、Bcrypt

This is currently used by our company. (But there are hidden dangers of outdated, it is recommended to replace)

(1 Introduction

bcrypt is a password hash function designed by Niels Provos and David Mazières based on the Blowfish cipher, and was proposed on USENIX in 1999.

The bcrypt function is the default password hashing algorithm for OpenBSD and other systems (including some Linux distributions, such as SUSE Linux).

(2) Use (Node.js)

installation:npm i bcryptjs

bcryptjsCompatible with C ++ bcrypt, but because it is written in pure JavaScript , it is slower (about 30%).

usage:

Sync 方法(Async 方法略):

const bcryptjs = require('bcryptjs');

// 1、生成 安全因子
const salt = bcrypt.genSaltSync(10);
// 2、执行 哈希函数
const password = bcryptjs.hashSync(plainPassword, bcryptjs.genSaltSync(salt));

// 另一种方法:快速执行
const SALT_FACTOR = 10;
const password = bcryptjs.hashSync(plainPassword, bcryptjs.genSaltSync(SALT_FACTOR));

// 3、比较是否相等
bcryptjs.compareSync(plainPassword, password);

Note: 安全因子The size of the value that appears in the code determines how slow the hash function will be. (Ie slow hash)

3、Scrypt

Never used, slightly.

4 、 Argon2

(1 Introduction

In 2013, NIST (National Institute of Standards and Technology) invited some cryptographers to hold it together 密码哈希竞赛 PHC(Password Hashing Competition). Argon2 won the championship in July 2015.

The competition lists the attack methods that the participating algorithms may face:

  • Hash algorithm cracking (restore original value, hash collision, etc.);
  • Lookup table / Rainbow table attack;
  • CPU optimization attack;
  • GPU, FPGA, ASIC and other dedicated hardware attacks;
  • Bypass attack
(2) Use (Node.js)

1. Preparation

You can skip this section if the prebuilt binaries work for you.

You MUST have a node-gyp global install before proceeding with install, along with GCC >= 5 / Clang >= 3.3. On Windows, you must compile under Visual Studio 2015 or newer.

node-argon2 works only and is tested against Node >=10.0.0.

--- 

OSX
To install GCC >= 5 on OSX, use homebrew:

$ brew install gcc
Once you've got GCC installed and ready to run, you then need to install node-gyp, you must do this globally:

$ npm install -g node-gyp
Finally, once node-gyp is installed and ready to go, you can install this library, specifying the GCC or Clang binary to use:

$ CXX=g++-6 npm install argon2
NOTE: If your GCC or Clang binary is named something different than g++-6, you'll need to specify that in the command.

2. Installation

npm i argon2


3. Use

const argon2 = require('argon2');

(async () => {
    try {
        // const hash = await argon2.hash("password");
        // 更多选项(以下都是默认值)
        const hash = await argon2.hash("password", {
            type: argon2.argon2i,
            hashLength: 32, // 哈希函数输出的字节长度(请注意,生成的哈希是使用Base64编码的,因此长度将增加约1/3)
            timeCost : 3, // 时间成本是哈希函数使用的通过次数(迭代次数)
            memoryCost: 2 ** 16, // 默认 4096(单位 KB,即 4MB)
            parallelism :1, //用于计算哈希值的线程数量。每个线程都有一个具有memoryCost大小的内存池
        })
        console.log("hash", hash)
        const is = await argon2.verify(hash, "password")
        console.log("is", is) // true
    } catch (err) {
        console.error("err", err)
    }
})()
(3) Parameters

1、type:

  • argon2d Faster and highly resistant to GPU attacks, which is useful for cryptocurrencies
  • argon2i It is slow and can resist tradeoff attacks, so it is preferred for password hashing and key derivation
  • argon2id Is a hybrid combination of the above, which can resist GPU and trade-off attacks

Because we are the hash for passwords, just use the default argon2i.


2. (Slow) Hash related parameters

memoryCostMemory overhead, which defines the memory usage

A good starting point is 0.75 * (RAM / number_of_users).

parallelismDegree of parallelism, which defines the number of threads

The best starting point is the number of cores.

timeCostTime overhead, which defines the execution time

It is recommended to run it on the system and determine the maximum parameters that match the memory and processor usage time limits.


As mentioned earlier, the essence is to strike a balance between security and usability .


3. Other parameters

salt: The default value is unset and will generate encrypted and secure random salt.
saltLength: Default 16.

version: You should not change this setting because the latest version is more powerful.

5. How password hashing solves the problem that ordinary hashing is easy to be cracked

The above describes two, to deal with ordinary hashes easy to crack the strategy , we can see how password hashes are applied and comply with these policies.

(1) For salt

Password hash using the CSPRNG(Cryptographically Secure Pseudo-Random Number Generator)密码学安全伪随机数生成器salt formation.

CSPRNG Yes 加密安全(Cryptographically Secure), (which means encrypted security) means that the random numbers generated with it are more random and unpredictable.

The ordinary computer random number algorithm is not very random.

Note: The salt value itself exists in the hashed string (in fact, it may also include the version, the number of slow hash iterations, etc.). When the method that compares with the plain text is called, the salt value is extracted inside the module for verification .

(2) For slow hashing

Bcryoy's security factor and Argon2's timeCost parameter are both for slow hash configuration.

6 Conclusion

The Bcrypt used by our company is actually insecure this year (2020). It is recommended to use Scrypt at least, with Argon2 conditionally .

Four, common problems


Question 1: I use my own to implement the hashing algorithm, and I do n’t need to make it publicly available.

Answer: Not recommended.

First introduce the cryptography 柯克霍夫原则(Kerckhoffs's principle, also known as the Kirkhoff hypothesis, axioms, or laws), proposed by August Kirkhoff in the 19th century: even if any details of the cryptosystem are known Know that as long as the key (key, also known as key or secret key) is not leaked, it should also be safe. Claude Shannon, the inventor of information theory, changed to say: "The enemy understands the system." Such a statement is called 香农箴言.

Based on this principle:

  • 1. It's weird to implement by yourself. After all, you are not a password expert. It is difficult to ensure that it is not cracked by bad guys (maybe it seems complicated after it is implemented by yourself, but it is actually easier to crack)
  • 2. If the code containing the hash algorithm leaks, it is very fragile and cannot be guaranteed to be cracked by bad guys.

Q2: Since it ’s all https now, the plaintext password that the front end sends to the back end is too lazy to add a hash, is it okay?

It is still recommended to hash the front end (although the hash algorithm of the front end is easy to expose). Don't miss any link.

Five, practical


Dropbox has publicly shared its own strategy for encrypting user account passwords, using three layers of encryption :

1、password

This is the clear text password.

2 、 SHA512

Doing SHA512 before bcrypt is because some bcrypt implementations will reduce the length of the hash value to 72 bytes, thereby reducing the entropy value of the password, while others allow variable-length passwords, which is vulnerable to DoS attacks. Using SHA512 hashing can get a fixed-length 512-byte hash value, avoiding the above two problems.

"Some others allow variable-length passwords, which makes them vulnerable to DoS attacks." I do n’t understand this sentence very much, and I ’ll write it.

3、bcrypt

As mentioned above, I won't go into details.

4、AES256

AES256 will use the key , commonly known as pepper . The key needs to be stored separately , preferably in an external system: such as a physically isolated server, or even a special hardware device (such as YubiHSM).

Here AES256 can also be replaced by HMAC. However, the former is more secure.

Guess you like

Origin www.cnblogs.com/xjnotxj/p/12716981.html
Recommended