PHP and password security

Insert picture description here

Encrypted password

Generally, the password should be encrypted before storing the user password (such as using MD5, SHA and other algorithms), and then stored in the database.

The code to encrypt the password with MD5 is as follows:

<?php
	$password = $_POST['password'];
	echo md5($password);
?>

The code to encrypt the password with SHA1 is as follows:

<?php
	$password = $_POST['password'];
	echo sha1($password);
?>
有一些攻击者将用户常用的密码总结 出来,再使用这些加密算法得出其加密后的值,
将加密后的值和原始密码保存起来,形成一张可通过密码对原文进行反查的数据表,称其为彩虹表。
攻击者只需要用彩虹表与加密后的密码比对,就能得到用户的原始密码。

It is not recommended to use weak encryption algorithms such as dex and MD5 to encrypt sensitive information such as passwords. The hash algorithm is recommended to use SHA256 or SHA512.

<?php
	$password = $_POST['password'];
	echo hash("sha256",$password);
?>

PHP has a built-in hash () function, you only need to pass the encryption method to the hash () function, and directly indicate the use of encryption methods such as SHA256 and SHA512.

Password plus salt

使用盐(salt)来混淆加密后的值。可以加大攻击者直接从字典密码库中碰撞除用户密码的难度。如果所有
用户的salt一样,且混淆方式已知,那么攻击者依然可以针对常见密码与salt混合生成一张具有针对性的彩虹表

In order to increase the safety factor, a random salt should be used. Each time the user's password is written (register or modify the password), a salt (a random character) is randomly generated, and the salt and the password are mixed (can be various mixed methods, Not just limited to connecting the two together), and then hash calculation. In this way, even if the attacker has a rainbow table, he cannot immediately guess which hash values ​​correspond to which regular passwords, because even if the user enters the regular password, the hash value of the salt mixture is different from the original password.

The code for encrypting user passwords using salting is as follows:

<?php
	$password = $_POST['password'];
	$salt = rand(1,10000);
	$password = sha1($password.$salt);
?>

However, in the case where salt is different for different users, it is difficult to generate a rainbow table for all users. But an attacker can still use a brute force method to decipher a password against a certain user. If the user's password length is short and all numbers, plus if the salt used is too simple, and the algorithms such as MD5 and SHA make the encryption process faster due to their own characteristics, it is easy to be cracked.

You can increase the number of iterations of ordinary MD5 and other fast algorithms to generate complex salts, or use a more complex encryption algorithm such as mcrypt, which forces the attacker to brute force and then take longer. Since the encryption algorithm is controlled to be subtle, the attacker's deciphering can be hit, and at the same time, the time of single user login authentication is not too long, this method can effectively solve the danger of the attacker deciphering the password.

The code for multiple encryption is as follows:

<?php

$password = MD5($_POST['password']);
$salt = MD5(rand(1,10000));
$password = sha1($password.$salt);

?>

The code to generate a longer, more complex random salt is as follows:

<?php

$password = $_POST['password''];
$salt = base64_encode(mcrypt_create_iv(32,MCRYPT_DEV_RANDOM);
$password = sha1($password.$salt);

?>

Use the password_hash () function to specify the second parameter as PASSWORD_BCRYPT to encrypt the password code as follows:

$password = password_hash($password,PASSWORD_BCRYPT);

In addition to the above methods, you can also use your own way to confuse the string to create a more complex password encryption method

<?php

if (defined("CRYPT_BLOWFISH") && (CRYPT_BLOWFISH){
	$salt = '$2y$11$' . substr(md5(uniqid(rand(), true)), 0, 22);
	echo crypt($password, $salt);
}

?>

bcrypt is actually a combination of blowfish and crypt () function. Determine whether blowfish is available through CRYPT_BLOWFISH, and then generate a salt. But here it should be noted that, crypt () must be the salt $2a$or $2y$the beginning

blowfish是区块加密算法中的对称加密的一种
crypt()函数返回使用DES、blowfish或MD5等算法加密的字符串。在不同的操作系统上,该函数的行为不同,某些操作系统支持一种以上的算法类型。

Prevent brute force

Brute-force Attract (Brute-force Attract), also known as exhaustive cracking, is a way of cracking passwords, that is to try to know the password one by one until the real password is found.

Common defense methods are as follows

(1)使用验证码进行验证登入
(2)使用Token生成form_hash,然后验证
(3)使用随机数时,要确保用户无法获取随机数生成算法。
(4)身份验证需要用户凭短信、邮件接受验证码时,需要对验证次数进行限制
(5)限制某时间段内验证此数
(6)用户在设置密码时要求用户使用特殊字符和字母数字组合,并限制最小长度

Random number security

随机数与密码一样,防止被预测,在各类业务场景中必不可少。随机数有真随机数和伪随机数之分。

True random numbers are generated using a true random number generator (TRNG), which is a random number generated using unpredictable physical methods, such as tossing coins, dice, runners, noise using electronic components, nuclear fission, etc.

Pseudo-random numbers are generated using a pseudo-random generator (PRNG), which is generated by a computer using certain algorithms or seeds. Computer generated pseudo-random numbers, which are divided into strong pseudo-random numbers (random numbers that are difficult to predict) and pseudo-random numbers (random numbers that are easy to predict).

The scenarios where random numbers are commonly used in projects include password salt generation, verification code generation, Token generation, UUID generation, key generation, digital signature generation, encryption vector generation, Nonce generation, etc.

加密向量(IV或SV)是一个固定长度地输入值,使用随机数产生地初始向量才能达到语义安全,并让攻击者难以对同一把密钥地的密文进行破解。在区块加密中,使用了初始向量的加密模式称为区块加密模式
Nonce是Number once的缩写,在密码学中Nonce是一个只被使用一次的任意或非重复的随机数值。

Improper use of random numbers can lead to a series of security problems.

(1)在研发过程中使用时间戳作为随机数[MD5(时间戳),MD5(用户ID+时间戳)],但是由于时间戳是可以
	预测的,因此很容易被破解。
(2)生成密码用的slat以及找回密码时的Token,需要一个随机数,如果直接根据用户ID生成Token,很容易
	被攻击者猜解。
(3)OAuth2.0中需要第三方传递一个state参数作为CSRF Token来防止CSRF攻击,很多研发人员根本不适用
	这个参数,或者时传入一个固定的值。由于认证方无法对这个值进行业务层面的有效性校验,导致了OAuth的CSRF攻击。
(4)在抽奖程序中如果使用的随机数不均匀或者可猜解,可直接造成奖品损失。
(5)PHP5在Windows操作系统下调用rand()函数的时候会发生随机数不均匀的情况,其他操作系统不会有这
	样的情况。PHP提供了另一个高质量、非常好的随机数发生器mt_rand(),在涉及项目安全的时候可选用
	这个函数。

Digital summary

Digital digest, also known as digital signature, is to convert a message of any length into a short message of fixed length. It is a one-way, irreversible encryption method. Generally, a single-hash function is used to "encrypt" a large plaintext that needs to be encrypted into a string of fixed-length ciphertext. This string of ciphertext is also known as a digital fingerprint. The length, and the results of different plain text digests into cipher texts are always different, and the same plain text digests must be consistent. Digital summaries are often used for encryption and authentication of information transmitted on the Internet for tamper-proof identification

The commonly used digital digest algorithms are MD5 and SHA.

Message Digest Algorithm MD5 (MD5) is a hash function widely used in the field of computer security to provide message integrity protection. MD5 is widely used in digital summaries because any changes to the original data, even if only one byte is modified, the resulting MD5 values ​​are very different. Moreover, given the original data and its MD5 value, it is very difficult to find a data with the same MD5 worth (ie, forged data).

Introduction to MAC and HMAC

Message Authentication Code (MAC) generates an encrypted digest through KEY on the basis of sending a message. It is usually used to detect whether a message has been tampered with during transmission. The MAC message authentication process is shown in the figure:
Insert picture description here

In message authentication, the sender of the message calculates the MAC data tag through the key and MAC, and then sends the message and MAC label to the receiver. Message recipients use the same key in turn to compare MAC tags generated by the same MAC algorithm. If they are the same, the recipient can assume that the message has not changed or tampered during transmission.

Simultaneously. To prevent replay attacks, the message itself must contain data that ensures that the same can only be sent once, such as using a time stamp
, serial number, or using a MAC once.

The hashed message authentication code (HMAC) is implemented by encrypting the hash algorithm based on the MAC algorithm.

Use hash_hmac () function to generate hash value for original message using MD5 method

<?php
	echo hash_hmac('ma5','LEO学PHP','php_secret_key');
?>

If you need to generate a hash value for a file, you can use the hash_hmac_file () function to generate the hash value using the SHA256 algorithm in the following example.

<?php
	echo hash_hmac('sha256','/tmp/LEO学PHP.pdf','php_secret_key');
?>

Symmetric encryption

Symmetric encryption algorithm means that the sender of the data encrypts the plaintext (original data) and the key together and sends it into a complex encrypted ciphertext. After the recipient receives the ciphertext, if he wants to interpret the original text, he needs to use the encryption key and the inverse algorithm of the same algorithm to interpret the ciphertext, so that it can be restored to a readable plaintext. The advantages of the symmetric encryption algorithm are that the algorithm is open, the calculation amount is small, the encryption speed is fast, and the encryption efficiency is high, which is suitable for the occasion of encrypting a large amount of data. Commonly used algorithms are DES, 3DES, TDEA, Blowfish, RC2, RC4, RC5, IDEA, SKIPJACK, AES and so on.

If you need to use symmetric encryption algorithm in PHP, you need the support of mcrypt extension. PHP's mcrypt extension provides a powerful encryption and decryption method. It can be displayed by the functions mcrypt_list_algorithms () and mcrypt_list + modes ().

<pre>
<?php
	$type_list = mcrypt_list_algorithms();	//mcrypt支持的加密算法列表
	$mode_list = mcrypt_list_modes();	//mcrypt支持的加密模式列表
	print_r($type_list);
	print_r($mode_list);
?>
</pre>

Insert picture description here

The code encrypted by DES is as follows:

<?php 

$auth_key = 'safe_key';
$salt = '!@#$%';
$content = 'Hello World';
$td = mcrypt_module_open(mcrypt_des,'','ecb','');	//使用mcrypt_des算法ecb模式

$iv_size = mcrypt_enc_get_iv_size($td);	//设置初始向量大小
$iv = mcrypt_create_iv($iv_size,mcrypt_rand);	//创建初始向量
$key_size = mcrypt_enc_get_key_size($td);	//返回所支持的最大密钥长度(以字节计算)

$key = substr(md5($auth_key.salt),0,$key_size);
mcrypt_generic_init($td, $key, $iv);	//初始化
$secret = mcrypt_generic($td, $content);	//加密并返回加密后的内容
echo base64_encode($secret);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);	//结束

 ?>

Insert picture description here

The code to decrypt using DES is as follows:

<?php 

$auth_key = 'safe_key';
$salt = '!@#$%';
$secret = 'Rr6TE6b1+XXiPkJnFUOuMw==';
$td = mcrypt_module_open(mcrypt_des,'','ecb','');	//使用mcrypt_des算法ecb模式

$iv_size = mcrypt_enc_get_iv_size($td);	//设置初始向量大小
$iv = mcrypt_create_iv($iv_size,mcrypt_rand);	//创建初始向量
$key_size = mcrypt_enc_get_key_size($td);	//返回所支持的最大密钥长度(以字节计算)

$key = substr(md5($auth_key.salt),0,$key_size);
mcrypt_generic_init($td, $key, $iv);	//初始化
$content = mdecrypt_generic($td, base64_decode($secret));	//解密并返回内容
echo $content;
mcrypt_generic_deinit($td);
mcrypt_module_close($td);	//结束

 ?>

Insert picture description here

AES is the abbreviation of Advanced Enctyption Standard (Advanced Encryption Standard), also known as Rijindael encryption method in cryptography, and is a block encryption standard adopted by the US federal government. This standard is used to replace the original DES, which has been analyzed by many parties and widely used worldwide.
AES currently has five encryption modes:

(1)电码本模式
(2)密码分组链接模式
(3)计数模式
(4)密码反馈模式
(5)输出反馈模式

In the mcrypt extension in PHP, rijndael-128, rijndael-192, and rijndael-256 are AES encryptions. The three types use different data blocks and key lengths for encryption.

In the AES ECB mode, 16 bytes are generally used as a block, and then the entire block is encrypted. If the input string is not enough for 16 bytes, it needs to be filled.

In the AES CBC encryption mode, the initialization vector (IV) needs to be added. The default value of zhi6 is 16 0s. Because it is block encryption, the IV of the next group uses the encrypted ciphertext of the previous group. The CFB and OFB modes are similar, but they are more complicated and more difficult to crack.

Asymmetric encryption

The symmetric encryption algorithm uses the same key for encryption and decryption. Unlike symmetric encryption algorithms, asymmetric encryption algorithms require two keys—public key (public key) and private key (private key) to encrypt and decrypt. The public key and the private key are a pair. If the public key is used to encrypt the data, only the corresponding private key can be used to decrypt; if the private key is used to encrypt the data, then only the corresponding public key can be decrypted.

The main algorithms used in asymmetric encryption are RSA, Elgamal, knapsack algorithm, Rabin, DH, ECC (elliptic curve encryption algorithm), etc. RSA is one of the most influential public key encryption algorithms at present, which can resist the current The vast majority of password attacks known to Zhi.

生成私钥
openssl genrsa -out rsa_private_key.pem 1024
生成公钥
openssl rsa -in rsa_private_key.pem -pubout-out rsa_public_key.pem
<?php 

$private_key_file = "rsa_private_key.pem";
$public_key_file = "rsa_public_key.pem";
$data = "Hello World";
if (file_exists($private_key_file)){
	$private_key_file = file_get_contents($private_key_file);
}
else{
	die('private key not exists');
}

if (file_exists($public_key_file)){
	$public_key = file_get_contents($public_key_file);
}
else{
	die('public key not exists');
}

$encrypted = $decrypted = "";
openssl_private_encrypt($data, $encrypted, $private_key);	//使用私钥加密数据
openssl_public_decrypt($encrypted, $decrypted, $public_key);
//使用公钥界面
echo $decrypted;
$encrypted = $decrypted = "";
openssl_public_encrypt($data, $encrypted, $public_key);//使用公钥进行加密
openssl_private_decrypt($data, $decrypted, $public_key);	//使用私钥进行加密
echo $decrypted;

 ?>

summary

It focuses on the application scenarios of various encryption methods and the security issues in the process of using passwords. According to different business scenarios, choose the correct encryption method to ensure user information security.

Published 71 original articles · Like 3 · Visits 4044

Guess you like

Origin blog.csdn.net/zouchengzhi1021/article/details/105341373