


Use PHP's built-in DES algorithm function to implement data encryption and decryption_PHP tutorial
Due to the needs of the project, it is necessary to write a class that can generate an "authorization code" (the authorization code mainly contains the expiration time of the project). The generated authorization code will be written to a file. Whenever When the project is running, the ciphertext in the file will be automatically read, and then a unique "key" will be used to call a function to decrypt the ciphertext and interpret the expiration time of the project.
Before, I tried to write it myself, mainly base64+md5+reverse string. The algorithm is too simple and can be easily cracked, and it fails to realize the importance of the "key" in encryption and decryption, so it is abandoned.
Later, I searched for relevant information and found that there is a powerful function library built into PHP, namely Mcrypt.
In fact, mcrypt itself provides powerful encryption and decryption methods, and supports many popular public encryption algorithms, such as DES, TripleDES, Blowfish (default), 3-WAY, SAFER-SK64, SAFER-SK128, TWOFISH, TEA, RC2 and GOST in CBC, OFB, CFB and ECB.
Here is a simple quote from Baidu Encyclopedia’s explanation of “encryption algorithm”:
The basic process of data encryption is to process files or data that were originally plain text according to a certain algorithm, turning it into an unreadable piece of code, usually called "ciphertext", so that it can only be entered when the corresponding password is entered. Only after entering the key can the original content be displayed. In this way, the purpose of protecting the data from being stolen and read by illegal persons is achieved. The reverse of this process is decryption, the process of converting the encoded information into its original data.
Encryption technologies are usually divided into two categories: "symmetric" and "asymmetric".
Symmetric encryption means that encryption and decryption use the same key, usually called "Session Key". This encryption technology is currently widely used. For example, the DES encryption standard adopted by the US government is a typical "symmetric encryption". "Encryption method, its Session Key length is 56Bits.
Asymmetric encryption means that encryption and decryption use different keys. There are usually two keys, called "public key" and "private key". They must be paired together, otherwise the encryption cannot be opened. document. The "public key" here means that it can be disclosed to the outside world, but the "private key" cannot, and can only be known by the holder. Its superiority lies here, because if the symmetric encryption method is transmitting encrypted files on the network, it will be difficult to tell the other party the key, and it may be eavesdropped no matter what method is used. The asymmetric encryption method has two keys, and the "public key" can be made public, so there is no fear of others knowing. The recipient only needs to use his own private key when decrypting, which is very good. This avoids key transmission security issues.
As mentioned earlier, mcrypt supports a variety of internationally public algorithms. In this project, I used the DES algorithm, DES (Data Encryption Standard), which is a symmetric algorithm, fast and suitable for encryption. Large amounts of data.
Introduction to several encryption functions used
Next, I will briefly explain several functions used in the encryption class.
1. resource mcrypt_module_open ( string $algorithm , string $algorithm_directory , string $mode , string $mode_directory )
- Parameter $algorithm: the algorithm to be used, you can view all supported algorithm names through the function mcrypt_list_algorithms()
- Parameter $mode: Which mode to use, similarly, you can build in the function mcrypt_list_algorithms() to view all supported modes
2. int mcrypt_enc_get_iv_size ( resource $td )
- This function will return the size of the initialization vector (IV) of the algorithm used (it looks a bit abstract), or 0 if the IV is ignored in the algorithm.
- The parameter $td is the return value of the mcrypt_module_open function.
3. string mcrypt_create_iv ( int $size [, int $source = MCRYPT_DEV_RANDOM ] )
This function will create an initialization vector (IV)
Parameters: $source can be MCRYPT_RAND, MCRYPT_DEV_RANDOM, MCRYPT_DEV_URANDOM
Note: PHP5.3.0 or above only supports MCRYPT_RAND
Return value: If successful, a string initial vector will be returned. If failed, False will be returned
4. int mcrypt_enc_get_key_size ( resource $td )
This function can obtain the maximum key length (in bytes) supported by the current algorithm
int mcrypt_generic_init ( resource $td , string $key , string $iv )
Before calling mcrypt_generic() or mdecrypt_generic(), you first need to call this function. This function can help us initialize the buffer to store encrypted data.
Parameter $key: key length. Remember, the current value of $key is smaller than the value returned by the function mcrypt_enc_get_key_size()
Question: Is the larger the value of $key, the better? If there is a classmate association, please help me answer this question.
5. string mcrypt_generic ( resource $td , string $data )
After completing the previous work, you can call this function to encrypt the data.
- Parameter $data: the data content to be encrypted
- Return value: Returns the encrypted ciphertext
6. bool mcrypt_generic_deinit ( resource $td )
This function can help us uninstall the currently used encryption module.
返回值:成功时返回 TRUE, 或者在失败时返回 FALSE.
7. string mdecrypt_generic ( resource $td , string $data )
该函数能够用来解密数据。
注意:解密后的数据可能比实际上的更长,可能会有后续的\0,需去掉
8. bool mcrypt_module_close ( resource $td )
关闭指定的加密模块资源句柄
返回值:成功时返回 TRUE, 或者在失败时返回 FALSE.
参考代码
<?php class authCode { public $ttl;//到期时间 时间格式:20120101(年月日) public $key_1;//密钥1 public $key_2;//密钥2 public $td; public $ks;//密钥的长度 public $iv;//初始向量 public $salt;//盐值(某个特定的字符串) public $encode;//加密后的信息 public $return_array = array(); // 返回带有MAC地址的字串数组 public $mac_addr;//mac地址 public $filepath;//保存密文的文件路径 public function __construct(){ //获取物理地址 $this->mac_addr=$this->getmac(PHP_OS); $this->filepath="./licence.txt"; $this->ttl="20120619";//到期时间 $this->salt="~!@#$";//盐值,用以提高密文的安全性 // echo "<pre class="brush:php;toolbar:false">".print_r(mcrypt_list_algorithms ()).""; // echo "
".print_r(mcrypt_list_modes()).""; } /** * 对明文信息进行加密 * @param $key 密钥 */ public function encode($key) { $this->td = mcrypt_module_open(MCRYPT_DES,'','ecb',''); //使用MCRYPT_DES算法,ecb模式 $size=mcrypt_enc_get_iv_size($this->td);//设置初始向量的大小 $this->iv = mcrypt_create_iv($size, MCRYPT_RAND);//创建初始向量 $this->ks = mcrypt_enc_get_key_size($this->td);//返回所支持的最大的密钥长度(以字节计算) $this->key_1 = substr(md5(md5($key).$this->salt),0,$this->ks); mcrypt_generic_init($this->td, $this->key_1, $this->iv); //初始处理 //要保存到明文 $con=$this->mac_addr.$this->ttl; //加密 $this->encode = mcrypt_generic($this->td, $con); //结束处理 mcrypt_generic_deinit($this->td); //将密文保存到文件中 $this->savetofile(); } /** * 对密文进行解密 * @param $key 密钥 */ public function decode($key) { try { if (!file_exists($this->filepath)){ throw new Exception("授权文件不存在"); }else{//如果授权文件存在的话,则读取授权文件中的密文 $fp=fopen($this->filepath,'r'); $secret=fread($fp,filesize($this->filepath)); $this->key_2 = substr(md5(md5($key).$this->salt),0,$this->ks); //初始解密处理 mcrypt_generic_init($this->td, $this->key_2, $this->iv); //解密 $decrypted = mdecrypt_generic($this->td, $secret); //解密后,可能会有后续的\0,需去掉 $decrypted=trim($decrypted) . "\n"; //结束 mcrypt_generic_deinit($this->td); mcrypt_module_close($this->td); return $decrypted; } }catch (Exception $e){ echo $e->getMessage(); } } /** * 将密文保存到文件中 */ public function savetofile(){ try { $fp=fopen($this->filepath,'w+'); if (!$fp){ throw new Exception("文件操作失败"); } fwrite($fp,$this->encode); fclose($fp); }catch (Exception $e){ echo $e->getMessage(); } } /** * 取得服务器的MAC地址 */ public function getmac($os_type){ switch ( strtolower($os_type) ){ case "linux": $this->forLinux(); break; case "solaris": break; case "unix": break; case "aix": break; default: $this->forWindows(); break; } $temp_array = array(); foreach( $this->return_array as $value ){ if (preg_match("/[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f]/i",$value,$temp_array )){ $mac_addr = $temp_array[0]; break; } } unset($temp_array); return $mac_addr; } /** * windows服务器下执行ipconfig命令 */ public function forWindows(){ @exec("ipconfig /all", $this->return_array); if ( $this->return_array ) return $this->return_array; else{ $ipconfig = $_SERVER["WINDIR"]."\system32\ipconfig.exe"; if ( is_file($ipconfig) ) @exec($ipconfig." /all", $this->return_array); else @exec($_SERVER["WINDIR"]."\system\ipconfig.exe /all", $this->return_array); return $this->return_array; } } /** * Linux服务器下执行ifconfig命令 */ public function forLinux(){ @exec("ifconfig -a", $this->return_array); return $this->return_array; } } $code=new authCode(); //加密 $code->encode("~!@#$%^"); //解密 echo $code->decode("~!@#$%^"); ?>

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1
Powerful PHP integrated development environment