Home Backend Development PHP Tutorial Example tutorial of ecshop's aes encryption (encapsulation)

Example tutorial of ecshop's aes encryption (encapsulation)

Jun 28, 2017 am 10:38 AM
ecshop encryption encapsulation

From a company that does shopex and ecstore to a company that does b2b ecshop... It’s time to put it into practice. Let’s not talk about other things. Let’s first understand what PHP’s AES encryption is?

aes (Advanced Encryption Standard), the block length of AES is fixed at 128 bits, and the key length can be 128, 192 or 256 bits; it is a reversible encryption method, different from md5.

AES is divided into several modes, such as ECB, CBC, CFB, etc. Except for ECB, which is not very safe because it does not use IV, the differences between other modes are not too obvious. Most of the differences are between IV and The method of KEY to calculate ciphertext is slightly different.

What is the role of iv?

IV is called the initial vector. The encrypted strings of different IVs are different. Encryption and decryption require the same IV. Since the IV looks the same as the key, there is one more IV. For the purpose For each block, the key remains unchanged, but only the IV of the first block is provided by the user, and other block IVs are automatically generated.
The length of IV is 16 bytes. If it exceeds or is insufficient, the libraries that may be implemented will complete or truncate it. But since the length of the block is 16 bytes, it can generally be considered that the required IV is 16 bytes.

Now that I have a certain understanding of aes, let’s start coding.

<?phpclass cryptaes{protected $cipher = MCRYPT_RIJNDAEL_128;protected $mode = MCRYPT_MODE_ECB;protected $pad_method = &#39;&#39;;protected $secret_key = &#39;&#39;;protected $iv = &#39;&#39;; public function set_cipher($cipher)
    {$this->cipher = $cipher;
    } public function set_mode($mode)
    {$this->mode = $mode;
    } public function set_iv($iv)
    {$this->iv = $iv;
    } public function set_key($key)
    {$this->secret_key = $key;
    } public function require_pkcs5()
    {$this->pad_method = 'pkcs5';
    } protected function pad_or_unpad($str, $ext)
    {if ( is_null($this->pad_method) )
        {return $str;
        }else{$func_name = __CLASS__ . '::' . $this->pad_method . '_' . $ext . 'pad';if ( is_callable($func_name) )
            {$size = mcrypt_get_block_size($this->cipher, $this->mode);return call_user_func($func_name, $str, $size);
            }
        }return $str;
    } protected function pad($str)
    {return $this->pad_or_unpad($str, '');
    } protected function unpad($str)
    {return $this->pad_or_unpad($str, 'un');
    }     //加密类public function encrypt($str)
    {print_r($str);$str = $this->pad($str);$td = mcrypt_module_open($this->cipher, '', $this->mode, ''); if ( empty($this->iv) )
        {$iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
        }else{$iv = $this->iv;
        }
 
        mcrypt_generic_init($td, $this->secret_key, $iv);$cyper_text = mcrypt_generic($td, $str);$rt=base64_encode($cyper_text);//$rt = bin2hex($cyper_text);mcrypt_generic_deinit($td);
        mcrypt_module_close($td); return $rt;
    }     //解密类public function decrypt($str){$td = mcrypt_module_open($this->cipher, '', $this->mode, ''); if ( empty($this->iv) )
        {$iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
        }else{$iv = $this->iv;
        }
 
        mcrypt_generic_init($td, $this->secret_key, $iv);//$decrypted_text = mdecrypt_generic($td, self::hex2bin($str));$decrypted_text = mdecrypt_generic($td, base64_decode($str));$rt = $decrypted_text;
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td); return $this->unpad($rt);
    } public static function hex2bin($hexdata) {$bindata = '';$length = strlen($hexdata);for ($i=0; $i < $length; $i += 2)
        {$bindata .= chr(hexdec(substr($hexdata, $i, 2)));
        }return $bindata;
    } public static function pkcs5_pad($text, $blocksize)
    {$pad = $blocksize - (strlen($text) % $blocksize);return $text . str_repeat(chr($pad), $pad);
    } public static function pkcs5_unpad($text)
    {$pad = ord($text{strlen($text) - 1});if ($pad > strlen($text)) return false;if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) return false;return substr($text, 0, -1 * $pad);
    }
}?>
Copy after login

The aes encryption and decryption packaging class is encapsulated and encrypted where needed:

require_once(ROOT_PATH . 'includes/lib_smt_cryptaes.php'); //ecshop引入文件方式$aes_obj     = new cryptaes();$iv         = '12345678baiducom';$privateKey = '12345678baiducom';$data['a'] =  ‘周二’;$data['b'] =  ‘周三’;$data['c'] =  ‘周四’;$da = json_encode($data);$aes_obj->set_key($privateKey);$aes_obj->require_pkcs5();$aes_obj->set_iv($iv);$il = $aes_obj->encrypt($da);//写入cookiesetcookie('il', $il,time()+360000); //加密结果$il
Copy after login

What I want to pass here is an array , it should be noted that aes can only encrypt strings. Needs to be converted to string.

         = ['il'(ROOT_PATH . 'includes/lib_smt_cryptaes.php'     =      = '12345678baiducom';         = '12345678baiducom'->set_key(->->set_iv( = ->decrypt( = json_decode(,);    
       print_r($j_token);//解密结果
Copy after login

This completes the encryption and transmission of aes.

We welcome everyone to ask questions, communicate and grow together.

The above is the detailed content of Example tutorial of ecshop's aes encryption (encapsulation). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year Apr 17, 2024 pm 08:00 PM

According to news from this site on April 17, TrendForce recently released a report, believing that demand for Nvidia's new Blackwell platform products is bullish, and is expected to drive TSMC's total CoWoS packaging production capacity to increase by more than 150% in 2024. NVIDIA Blackwell's new platform products include B-series GPUs and GB200 accelerator cards integrating NVIDIA's own GraceArm CPU. TrendForce confirms that the supply chain is currently very optimistic about GB200. It is estimated that shipments in 2025 are expected to exceed one million units, accounting for 40-50% of Nvidia's high-end GPUs. Nvidia plans to deliver products such as GB200 and B100 in the second half of the year, but upstream wafer packaging must further adopt more complex products.

How to set up encryption of photo album on Apple mobile phone How to set up encryption of photo album on Apple mobile phone Mar 02, 2024 pm 05:31 PM

In Apple mobile phones, users can encrypt photo albums according to their own needs. Some users don't know how to set it up. You can add the pictures that need to be encrypted to the memo, and then lock the memo. Next, the editor will introduce the method of setting up the encryption of mobile photo albums for users. Interested users, come and take a look! Apple mobile phone tutorial How to set up iPhone photo album encryption A: After adding the pictures that need to be encrypted to the memo, go to lock the memo for detailed introduction: 1. Enter the photo album, select the picture that needs to be encrypted, and then click [Add to] below. 2. Select [Add to Notes]. 3. Enter the memo, find the memo you just created, enter it, and click the [Send] icon in the upper right corner. 4. Click [Lock Device] below

How to set a password for folder encryption without compression How to set a password for folder encryption without compression Feb 20, 2024 pm 03:27 PM

Folder encryption is a common data protection method that encrypts the contents of a folder so that only those who have the decryption password can access the files. When encrypting a folder, there are some common ways to set a password without compressing the file. First, we can use the encryption function that comes with the operating system to set a folder password. For Windows users, you can set it up by following the following steps: Select the folder to be encrypted, right-click the folder, and select "Properties"

AMD 'Strix Halo” FP11 package size exposed: equivalent to Intel LGA1700, 60% larger than Phoenix AMD 'Strix Halo” FP11 package size exposed: equivalent to Intel LGA1700, 60% larger than Phoenix Jul 18, 2024 am 02:04 AM

This website reported on July 9 that the AMD Zen5 architecture "Strix" series processors will have two packaging solutions. The smaller StrixPoint will use the FP8 package, while the StrixHalo will use the FP11 package. Source: videocardz source @Olrak29_ The latest revelation is that StrixHalo’s FP11 package size is 37.5mm*45mm (1687 square millimeters), which is the same as the LGA-1700 package size of Intel’s AlderLake and RaptorLake CPUs. AMD’s latest Phoenix APU uses an FP8 packaging solution with a size of 25*40mm, which means that StrixHalo’s F

How to encrypt the compressed package in winrar-winrar encrypted compressed package method How to encrypt the compressed package in winrar-winrar encrypted compressed package method Mar 23, 2024 pm 12:10 PM

The editor will introduce to you three methods of encryption and compression: Method 1: Encryption The simplest encryption method is to enter the password you want to set when encrypting the file, and the encryption and compression are completed. Method 2: Automatic encryption Ordinary encryption method requires us to enter a password when encrypting each file. If you want to encrypt a large number of compressed packages and the passwords are the same, then we can set automatic encryption in WinRAR, and then just When compressing files normally, WinRAR will add a password to each compressed package. The method is as follows: Open WinRAR, click Options-Settings in the setting interface, switch to [Compression], click Create Default Configuration-Set Password Enter the password we want to set here, click OK to complete the setting, we only need to correct

How do C++ functions improve the efficiency of GUI development by encapsulating code? How do C++ functions improve the efficiency of GUI development by encapsulating code? Apr 25, 2024 pm 12:27 PM

By encapsulating code, C++ functions can improve GUI development efficiency: Code encapsulation: Functions group code into independent units, making the code easier to understand and maintain. Reusability: Functions create common functionality that can be reused across applications, reducing duplication and errors. Concise code: Encapsulated code makes the main logic concise and easy to read and debug.

How to decrypt the encrypted computer version of EZVIZ Cloud Video? -EZVIZ Cloud Video PC version exits full screen? How to decrypt the encrypted computer version of EZVIZ Cloud Video? -EZVIZ Cloud Video PC version exits full screen? Mar 18, 2024 pm 12:25 PM

How to de-encrypt videos on EZVIZ Cloud: There are many ways to de-encrypt videos on EZVIZ Cloud, one of which is by using the EZVIZ Cloud Mobile App. Users only need to enter the device list, select the camera to be decrypted and enter the device details page. On the device details page, find the &quot;Settings&quot; option, and then select &quot;Video Encryption&quot; to make relevant settings. In the video encryption settings interface, you can choose the option to turn off video encryption, and save the settings to complete the decryption operation. This simple step allows users to easily decrypt videos and improves the convenience of using the camera. If you use the computer client of EZVIZ Cloud, you can also cancel video encryption through similar steps. Just log in and select the corresponding camera, enter the device details interface, and then look for video addition in the settings.

Analog, a new project by crypto veterans: raised $16 million, with airdrop expected Analog, a new project by crypto veterans: raised $16 million, with airdrop expected Feb 22, 2024 pm 04:50 PM

Original author: Meteor, ChainCatcher Original editor: Marco, ChainCatcher Recently, the full-chain interoperability protocol Analog has entered the public eye with the disclosure of US$16 million in financing. Investment institutions include TribeCapital, NGCVentures, Wintermute, GSR, NEAR, OrangeDAO, and Mike Novogratz’s Alternative asset management companies Samara Asset Group, Balaji Srinivasan, etc. At the end of 2023, Analog caused some excitement in the industry. They released information on the open testnet registration event on the X platform.

See all articles