Three common encryption functions in PHP

Posted by DavidAM on Fri, 15 May 2020 12:03:01 +0200

PHP encryption function - md5() function encryption instance usage

MD5() function is the MD5 hash value of calculator string. Using MD5 algorithm, the full name of MD5 is message digest algorithm 5. Its function is to calculate data information of different length into a 128 bit value through a series of algorithms, that is, to change a byte string of any length into a large integer of a certain length. Note that this is a "byte string" rather than a "string" because this transformation is only related to the value of the byte, not to the character set or encoding.

If the second parameter is set to true, the function will return a ciphertext in binary form, which defaults to false.

In many websites, the password to register user name is used MD5 encryption, and then saved to the database. When the user name logs in, the program calculates the password entered by the user into the MD5 value, and then compares it with the MD5 value saved in the database. In this process, the program itself will not "know" the real password of the user, thus ensuring the personal privacy of the registered user and improving the security.

 

The following example implements the function of registration and login. After MD5 encryption, save the database. The specific steps are as follows:

Step 1: create the conn.php file and complete the link with the database:

<?php
header("Content-Type:text/html;charset=utf-8");

$conn = mysqli_connect('localhost','root','123456') or die('Database connection failed'.mysqli_error());
mysqli_select_db($conn,'tp5');
mysqli_query($conn,'set name utf-8');

Step 2: create the register.php file, simulate the data in the form, encrypt the password through the MD5() function, and use the object-oriented method. The reference code is as follows:

<?php
header("Content-Type:text/html;charset=utf-8");

class CHECKUSER{
    var $name;
    var $pwd;

    function __construct($x,$y){
        $this->name = $x;
        $this->pwd = $y;
    }

    function checkinput(){
        include 'conn.php';
        $info = mysqli_query($conn,'insert into user(username,password) value("'.$this->name.'","'.md5($this->pwd).'")');

        if($info == false){
            echo "<script>alert('Member registration failed');history.back();</script>";
            exit();
        }else{
            $_SESSION['admin_name'] = $this->name;
            echo "<script>alert('Member registration successful');window.location.href='demo.php';</script>";
        }
    }
}

$_POST['name'] = 'cyy2';
$_POST['password'] = '123';
$obj = new CHECKUSER(trim($_POST['name']),trim($_POST['password']));
$obj->checkinput();

After completion, you can view the encrypted password in the database!

 

PHP encryption function -- example usage of sha1() function encryption

The full name of Sha is: Secure Hash Algorithm is mainly applicable to Digital Signature Algorithm DSA defined in Digital Signature Standard DSS. For messages less than 2 ^ 64 bits in length, SHA1 generates a 160 bit message summary. When a message is received, the message digest can be used to verify the integrity of the data. In the process of transmission, the data is likely to change, so different message summaries will be generated at this time. The sha1() function provided by PHP uses Sha algorithm!

The function returns a 40 bit hexadecimal number. If the parameter raw Ou output is true, a 20 bit binary number will be returned. The default value is raw Ou output is false.

Here we will focus on:

The 1 after sha is the 1 in the Arabic numeral (123456), not the letter L (L). Many people will think of it as a letter, but it is an Arabic numeral. You must pay attention here, don't get it wrong!

<?php
header("Content-Type:text/html;charset=utf-8");

$str = 'cyy';
echo 'true--Original 20 character binary format:'.sha1($str,TRUE).'<br>';
echo 'false--40 Character hex format:'.sha1($str).'<br>';

The output result is:

 

 

The following example is the result of outputting sha1() and testing it:

<?php
header("Content-Type:text/html;charset=utf-8");

$str = 'cyy';
echo 'false--40 Character hex format:'.sha1($str).'<br>';
if(sha1($str) == 'f1ff58f24616c02df26e8d8393887364bfb4b486'){
    echo 'i love cyy';
    exit;
}

The output result is:

 

 

The following example is the comparison of MD5 and SHA encryption operations, with the code as follows:

<?php
header("Content-Type:text/html;charset=utf-8");

$str = 'cyy';
echo 'sha1: '.sha1($str).'<br>';
echo 'md5: '.md5($str).'<br>';

The output result is:

 

 

PHP encryption function - crypt() function encryption usage example

Data encryption principle: it is to process the original open file or data according to some algorithm, making it an unreadable code, usually called "ciphertext", so as to protect the data from being stolen and read illegally!

The main functions that can encrypt data in PHP are: crypt(), md5(), sha1(), and the encryption extension library, Mcrpyt and Mash.

crypt() function can complete one-way encryption function, which is one-way string hash

By default, PHP uses one or two characters of DES interference string. If the system uses MD5, it will use 12 characters. You can view the length of interference string currently used through crypt ﹣ salt ﹣ length variable!

<?php
header("Content-Type:text/html;charset=utf-8");

$str = 'cyy';
echo 'Before encryption:'.$str.'<br>';
echo 'After encryption:'.crypt($str).'<br>';

The output is as follows:

 

 

After the above instance is executed, the browser is refreshed all the time. You will find that the encryption result generated each time is different. Then how to judge the encrypted data becomes a problem. The crypt() function is one-way encrypted, the ciphertext cannot be restored to plaintext, and the data after each encryption is different, which is the problem to be solved by the salt parameter.

The crypt() function encrypts the plaintext with the salt parameter. When judging, it encrypts the output information with the same salt parameter again, and judges by comparing the results after two encryptions!

The following example checks the input user name. The specific code is as follows:

<?php
header("Content-Type:text/html;charset=utf-8");

include 'conn.php';
?>

<form name="form1" action="#" method="post">
    <input type="text" name="username" id="username" size="15">
    <input type="submit" name="Submit" value="testing">
</form>

<?php
if(isset($_POST['username']) != ''){
    $user = crypt(isset($_POST['username']),'cyy');
    $sql = "select * from user where username = '".$user."'";
    $res = mysqli_query($conn,$sql);
    if($res){
        echo 'User name already exists';
    }else{
        echo 'User name available';
    }
}

Topics: PHP SHA1 Database SQL