search
HomeBackend DevelopmentPHP TutorialParsing of AES encrypted files in PHP (with code)

The content of this article is about the analysis of AES encrypted files in PHP (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

AES Introduction

Advanced Encryption Standard (AES, Advanced Encryption Standard) is the most common symmetric encryption algorithm (WeChat applet encrypted transmission uses this encryption algorithm) . Symmetric encryption algorithms use the same key for encryption and decryption.

Symmetric encryption
The keys used for encryption and decryption are the same. This encryption method is very fast and suitable for occasions where data is frequently sent. The disadvantage is that the transmission of the key is more troublesome. Secret keys are easily leaked.

Asymmetric encryption
The keys used for encryption and decryption are different. This encryption method is constructed using difficult mathematical problems. Usually the speed of encryption and decryption is relatively small. Slow, suitable for occasionally sending data. The advantage is that key transmission is convenient. Common asymmetric encryption algorithms are RSA, ECC and EIGamal.

Note:
PHP7.2 has deleted the Mcrypt extension, and the OpenSSL extension is used here.

<?php /*
* AES 算法    
*/class Aes {

    private $hex_iv = &#39;00000000000000000000000000000000&#39;; 

    private $key = &#39;397e2eb61307109f6e68006ebcb62f98&#39;;    
    function __construct($key) {
        $this->key = $key;        
        $this->key = hash(&#39;sha256&#39;, $this->key, true);
    }    /*
    * 字符串加密 不写入文件 
    */
    public function encrypt($input)
    {
        $data = openssl_encrypt($input, &#39;AES-256-CBC&#39;, $this->key, OPENSSL_RAW_DATA, $this->hexToStr($this->hex_iv));        
        $data = base64_encode($data);        
        return $data;
    }    /*
    * aes 给PHP文件加密
    * 写入设置文件
    */
    public function filecrypt($filename)
    {
        $type=strtolower(substr(strrchr($filename,&#39;.&#39;),1));            
        if (&#39;php&#39; == $type && is_file($filename) && is_writable($filename)) {  
                 $contents = file_get_contents($filename);                 
                 // echo $contents;exit;  
                 $contents = php_strip_whitespace($filename);                 
                 // echo $contents;exit;
                 // $headerPos = strpos($contents,&#39;<?php&#39;);
                 // echo $headerPos;exit;


                 // $contents = substr($contents, $headerPos + 5, $footerPos - $headerPos);
                 // echo $contents;
                 exit;
                 $data = openssl_encrypt($contents, &#39;AES-256-CBC&#39;, $this->key, OPENSSL_RAW_DATA, $this->hexToStr($this->hex_iv));                 
                 // echo $data;exit;
                 $data = base64_encode($data);                
                  // echo $data;exit;
                 return file_put_contents($filename, $data);  
            }  
                 return false;  
    }    /*
    * 字符串解密
    */
    public function decrypt($input)
    {
        $decrypted = openssl_decrypt(base64_decode($input), &#39;AES-256-CBC&#39;, $this->key, OPENSSL_RAW_DATA, $this->hexToStr($this->hex_iv));        
        return $decrypted;
    }    /*
      For PKCS7 padding
     */

    private function addpadding($string, $blocksize = 16) {

        $len = strlen($string);        
        $pad = $blocksize - ($len % $blocksize);        
        $string .= str_repeat(chr($pad), $pad);        
        return $string;

    }    private function strippadding($string) {

        $slast = ord(substr($string, -1));        
        $slastc = chr($slast);        
        $pcheck = substr($string, -$slast);        
        if (preg_match("/$slastc{" . $slast . "}/", $string)) {            
        $string = substr($string, 0, strlen($string) - $slast);            
        return $string;

        } else {            
        return false;

        }

    }    
    function hexToStr($hex)
    {

        $string=&#39;&#39;;        
        for ($i=0; $i < strlen($hex)-1; $i+=2)

        {            
        $string .= chr(hexdec($hex[$i].$hex[$i+1]));

        }        
        return $string;
    }

}
$key = &#39;397e2eb61307109f6e68006ebcb62f98&#39;;
$aes = new Aes($key);
$filename = __DIR__.&#39;\exchange.php&#39;;
// $filename = &#39;Y6RCuF6ETPC5J57hfhxovg==&#39;;
// 加密
$string = $aes->filecrypt($filename);
// echo $string;
echo "OK,加密完成!" ;

2. Simple function to encrypt PHP files

<?php  

 function encode_file_contents($filename) {  
     $type=strtolower(substr(strrchr($filename,&#39;.&#39;),1));  
     if (&#39;php&#39; == $type && is_file($filename) && is_writable($filename)) { // 如果是PHP文件 并且可写 则进行压缩编码  
         $contents = file_get_contents($filename); // 判断文件是否已经被编码处理  
         $contents = php_strip_whitespace($filename);   

         // 去除PHP头部和尾部标识  
         $headerPos = strpos($contents,&#39;<?php&#39;);  
         $footerPos = strrpos($contents,&#39;?>&#39;);  
         $contents = substr($contents, $headerPos + 5, $footerPos - $headerPos);  
         $encode = base64_encode(gzdeflate($contents)); // 开始编码  
         $encode = &#39;<?php&#39;."\n eval(gzinflate(base64_decode("."&#39;".$encode."&#39;".")));\n\n?>";   

         return file_put_contents($filename, $encode);  
     }  
     return false;  
 }   

 //调用函数
 // echo __DIR__.&#39;\server.php&#39;;   
 $filename = __DIR__.&#39;\server.php&#39;;  
 encode_file_contents($filename);  
 echo "OK,加密完成!" ;

Recommended related articles:

Request codes for post mode and get mode in curl of php

How to convert json object to array in thinkphp5 (code)

The above is the detailed content of Parsing of AES encrypted files in PHP (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Define the term 'session hijacking' in the context of PHP.Define the term 'session hijacking' in the context of PHP.Apr 29, 2025 am 12:33 AM

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

What is the full form of PHP?What is the full form of PHP?Apr 28, 2025 pm 04:58 PM

The article discusses PHP, detailing its full form, main uses in web development, comparison with Python and Java, and its ease of learning for beginners.

How does PHP handle form data?How does PHP handle form data?Apr 28, 2025 pm 04:57 PM

PHP handles form data using $\_POST and $\_GET superglobals, with security ensured through validation, sanitization, and secure database interactions.

What is the difference between PHP and ASP.NET?What is the difference between PHP and ASP.NET?Apr 28, 2025 pm 04:56 PM

The article compares PHP and ASP.NET, focusing on their suitability for large-scale web applications, performance differences, and security features. Both are viable for large projects, but PHP is open-source and platform-independent, while ASP.NET,

Is PHP a case-sensitive language?Is PHP a case-sensitive language?Apr 28, 2025 pm 04:55 PM

PHP's case sensitivity varies: functions are insensitive, while variables and classes are sensitive. Best practices include consistent naming and using case-insensitive functions for comparisons.

How do you redirect a page in PHP?How do you redirect a page in PHP?Apr 28, 2025 pm 04:54 PM

The article discusses various methods for page redirection in PHP, focusing on the header() function and addressing common issues like "headers already sent" errors.

See all articles

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

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software