The application scenarios are as follows: unique identification of users (article encryption ID prevents crawler), generation of regular code, and encryption of login password

Encrypt demo with Hashids (unique identifiers of users, article encryption ids to prevent crawlers)

Conversion encryption between strings and hexadecimal (generates regular code)

   /** * String to hexadecimal *@param $string
     * @return string
     */
    public function str_encode($string)
    {
        $hex="";
        for($i=0; $i<strlen($string); $i++){ $hex.=dechex(ord($string[$i])); } $hex=strtolower($hex);return $hex;
    }

   /** * Hexadecimal conversion string *@param $hex
     * @return string
     */
    public function str_decode($hex){
        $string="";
        for($i=0; $i<strlen($hex)- 1; $i+=2){
            $string.=chr(hexdec($hex[$i].$hex[$i+1]));
        }
        return  $string;
    }
Copy the code

When the user logs in to the account and password, it is transmitted in plaintext, as shown in the figure below:

Encrypt the login password


    / * * * to generate the key and iv address: https://asecuritysite.com/encryption/keygen * https://asecuritysite.com/encryption/PBKDF2z * /
     
    / * * *@paramString $string Specifies the character string to be encrypted@return string
     */
    public function encrypt($string)
    {
        // Openssl_encrypt Encrypts different McRypts. The length of the key must be longer than 16
        $data = openssl_encrypt($string, 'AES-192-CBC',pack('H*', env('ENCRYPT_KEY')), OPENSSL_RAW_DATA,pack('H*', env('ENCRYPT_IV')));

        $data = base64_encode($data);
        return $data;
    }
    / * * *@paramString $string String to decrypt *@return string
     */
    public function decrypt($string)
    {
        $decrypted = openssl_decrypt(base64_decode($string), 'AES-192-CBC',  pack('H*', env('ENCRYPT_KEY')), OPENSSL_RAW_DATA,pack('H*', env('ENCRYPT_IV')));

        return $decrypted;
    }
Copy the code
ENCRYPT_KEY=ENCRYPT_KEY
ENCRYPT_IV=ENCRYPT_IV
Copy the code

Aes-192-cbc encryption is used above

AES:

Aes is block-based encryption, that is, one piece (16 bytes) of data is processed at a time and filled in when the data is not a multiple of 16 bytes. This is called a block cipher (as opposed to bit-based stream ciphers), where 16 bytes is the block length

Several modes of packet encryption:

ECB: A basic encryption method in which ciphertext is divided into blocks of equal length (not complete) and then encrypted individually and output one by one.

CBC: it is a cyclic mode in which the ciphertext of the previous group and the plaintext of the current group are encrypted after xor operations. The purpose of this mode is to increase the difficulty of cracking.

CFB/OFB: This is actually a feedback mode designed to make cracking more difficult.

The encryption results of FCB and CBC are different, their modes are different, and CBC will add an initialization vector to the first cipher block operation.