search
HomeBackend DevelopmentPHP TutorialEncryption and decryption of php code

PHP code encryption class
  1. /*
  2. * @auther:wangyaofeng
  3. * @time:2014.11.6
  4. * @action: Encrypt the php project. Note that if there is a framework directory in the project or not Please move out the directories that need to be encrypted in advance
  5. * */
  6. class Encryption{
  7. private $c='';//Storage ciphertext
  8. private $s='',$q1,$q2,$q3,$q4,$ q5,$q6;//Storage the generated encrypted file content
  9. //If you do not set a value, isset will indicate that it does not exist;
  10. private $file='';//The path to read the file
  11. private $source= '',$target='';
  12. //Constructor, called to initialize global variables during instantiation;
  13. public function __construct(){
  14. //Initialize global variables
  15. $this->initialVar();
  16. //echo "hello n";
  17. }
  18. /*
  19. *@input $property_name,$value
  20. *@output
  21. * Magic method to set the value of variables; it can be processed according to needs. If the if judgment is directly removed, it means that the value of any attribute can be set, including attributes that do not exist;
  22. */
  23. public function __set($property_name,$value){
  24. //defined variables;
  25. if(isset($this- >$property_name)){
  26. $this->$property_name = $value;
  27. }else{
  28. //Exception handling, processing undeclared variable assignment; can be processed according to needs.
  29. throw new Exception("property does not exist");
  30. }
  31. }
  32. //Magic method to get the value of the variable;
  33. public function __get($property_name){
  34. if(isset($this->$property_name)) {
  35. return $this->$property_name;
  36. }else{
  37. //throw new Exception("property does not exist");
  38. return NULL;
  39. }
  40. }
  41. //Get random order
  42. private function RandAbc($ length=""){//Retrieve in random order
  43. $str="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  44. return str_shuffle($str);
  45. }
  46. //Encrypt the plain text content
  47. private function ciphertext($filename){
  48. / /$filename='index.php';
  49. $T_k1=$this->RandAbc();
  50. $T_k2=$this->RandAbc();
  51. $vstr=file_get_contents($filename);
  52. $v1= base64_encode($vstr);
  53. $c=strtr($v1,$T_k1,$T_k2);
  54. $this->c=$T_k1.$T_k2.$c;
  55. return $this;
  56. }
  57. //Initialization Variable
  58. private function initialVar(){
  59. $this->q1="O00O0O";//base64_decode
  60. $this->q2="O0O000";//$c (the original ciphertext after strtr replacement, by Target character + replacement character + base64_encode('original content'))
  61. $this->q3="O0OO00";//strtr
  62. $this->q4="OO0O00";//substr
  63. $this-> ;q5="OO0000";//52
  64. $this->q6="O00OO0";//urldecode parsed string (n1zb/ma5vt0i28-pxuqy*6%6Crkdg9_ehcswo4+f37j)
  65. }
  66. //Generate Encrypted template (complex version);
  67. private function model(){
  68. //$c = $this->c;
  69. //$this->initialVar();
  70. $this->s=' q6.'=urldecode("%6E1%7A%62%2F%6D%615%5C%76%740%6928%2D%70%78%75%71% 79%2A6%6C%72%6B%64%679%5F%65%68%63%73%77%6F4%2B%6637%6A");$'.
  71. $this->q1.'=$ '.$this->q6.'{3}.$'.$this->q6.'{6}.$'.$this->q6.'{33}.$'.$this- >q6.'{30};$'.$this->q3.'=$'.$this->q6.'{33}.$'.$this->q6.'{10} .$'
  72. .$this->q6.'{24}.$'.$this->q6.'{10}.$'.$this->q6.'{24};$'. $this->q4.'=$'.$this->q3.'{0}.$'.$this->q6.'{18}.$'.$this->q6.' {3}.$'.$this->q3.'{0}
  73. .$'.$this->q3.'Xiaobei.$'.$this->q6.'{24};$ '.$this->q5.'=$'.$this->q6.'{7}.$'.$this->q6.'{13};$'.$this->q1 .'.=$'.$this->q6.'{22}.$'.$this->q6.'{36}
  74. .$'.$this->q6.'{29}. $'.$this->q6.'{26}.$'.$this->q6.'{30}.$'.$this->q6.'{32}.$'.$this ->q6.'{35}.$'.$this->q6.'{26}.$'.$this->q6.'{30};
  75. eval($'.$this-> ;q1.'("'.base64_encode('$'.$this->q2.'="'.$this->c.'";
  76. eval('?>'.$'.$this ->q1.'($'.$this->q3.'($'.$this->q4.'($'.$this->q2.',$'.$this-> ;q5.'*2),$'.$this->q4.'($'.$this->q2.',$'.$this->q5.',$'.$this- >q5.'),
  77. $'.$this->q4.'($'.$this->q2.',0,$'.$this->q5.')))); ').'"));?>';
  78. return $this;
  79. }
  80. //Create encrypted file
  81. private function build($target){
  82. //$this->encodes("./index. php");
  83. //$this->model();
  84. $fpp1 = fopen($target,'w');
  85. fwrite($fpp1,$this->s) or die('write is fail!');
  86. fclose($fpp1);
  87. return $this;
  88. }
  89. //Encryption processing coherent operation
  90. public function encode($file,$target){
  91. //$file = "index.php";
  92. / /The coherent operation is actually to use the function to return to itself after processing
  93. $this->ciphertext($file)->model()->build($target);
  94. echo 'encode------'. $target.'-----ok
    ';
  95. }
  96. //Decrypt
  97. public function decode($file,$target=''){
  98. //Read the file to be decrypted
  99. $fpp1 = file_get_contents($file);
  100. $this->decodeMode($fpp1)->build($target);
  101. echo 'decode------'.$target.'-----ok';
  102. }
  103. //Decrypt the template and get the decrypted text
  104. private function decodeMode($fpp1){
  105. //Use eval as the flag to intercept it into an array, the first half is the replaced function name in the ciphertext , the second half is the ciphertext
  106. $m = explode('eval',$fpp1);
  107. //Execute the replacement part of the system function and get the system variable
  108. $varStr = substr($m[0],strpos( $m[0],'$'));
  109. //After execution, the replaced system function name can be used later
  110. eval($varStr);
  111. //Determine whether there is ciphertext
  112. if(!isset($ m[1])){
  113. return $this;
  114. }
  115. //Intercept the ciphertext {$this->q4} substr
  116. $star = strripos($m[1],'(');
  117. $end = strpos($m[1],')');
  118. $str = ${$this->q4}($m[1],$star,$end);
  119. //Decrypt the ciphertext {$this->q1} base64_decode
  120. $str = ${$this->q1}($str);
  121. //Intercept the decrypted core ciphertext
  122. $evallen = strpos($str,'eval' );
  123. $str = substr($str,0,$evallen);
  124. //Execute the core ciphertext so that the system variable is assigned the value $O0O000
  125. eval($str);
  126. //The following paragraph cannot be encapsulated because ${$this->qn} does not work in the whole text
  127. $this->s = ${$this->q1}(
  128. ${$this->q3}(
  129. ${$this ->q4}(
  130. ${$this->q2},${$this->q5}*2
  131. ),
  132. ${$this->q4}(
  133. ${$this-> q2},${$this->q5},${$this->q5}
  134. ),
  135. ${$this->q4}(
  136. ${$this->q2},0,$ {$this->q5}
  137. )
  138. )
  139. );
  140. return $this;
  141. }
  142. //Recursively read and create the target directory structure
  143. private function targetDir($target){
  144. if(!empty($target ) ) {
  145. if(!file_exists($target)){
  146. mkdir($target,0777,true);
  147. }else{
  148. chmod($target,0777);
  149. }
  150. }
  151. }
  152. //Recursion Decrypt Decrypt php files in the specified folder
  153. public function decodeDir($source,$target=""){
  154. if(is_dir($source)){
  155. $this->targetDir($target);
  156. $dir = opendir($source);
  157. while(false!=$file=readdir($dir))
  158. {
  159. //List all files and remove '.' and '..' The example used here is the thinkphp framework, Therefore, the Thinkphp directory is excluded by default. Users can set it according to their own needs
  160. if($file!='.' && $file!='..' && $file !='ThinkPHP')
  161. {
  162. $path = $target .DIRECTORY_SEPARATOR.$file;
  163. $sourcePath = $source.DIRECTORY_SEPARATOR.$file;
  164. $this->decodeDir($sourcePath,$path);
  165. }
  166. }
  167. }else if(is_file($source)){
  168. $extension=substr($source,strrpos($source,'.')+1);
  169. if(strtolower($extension)=='php'){
  170. $this->decode($source,$target );
  171. }else{
  172. //Files that are not PHP will not be processed
  173. copy($source, $target);
  174. }
  175. //return;
  176. }
  177. }
  178. //Recursive encryption encrypts php files in the specified folder
  179. public function encodeDir($source,$target){
  180. if(is_dir($source)){
  181. $this->targetDir($target);
  182. $ dir = opendir($source);
  183. while(false!=$file=readdir($dir))
  184. {
  185. //List all files and remove '.' and '..'
  186. if($file!=' .' && $file!='..' && $file !='ThinkPHP')
  187. {
  188. $path = $target.DIRECTORY_SEPARATOR.$file;
  189. $sourcePath = $source.DIRECTORY_SEPARATOR.$file;
  190. $this- >encodeDir($sourcePath,$path);
  191. }
  192. }
  193. }else if(is_file($source)){
  194. $extension=substr($source,strrpos($source,'.')+1);
  195. if(strtolower($extension)=='php'){
  196. $this->encode($source,$target);
  197. }else{
  198. copy($source, $target);
  199. }
  200. }
  201. }
  202. }
  203. $ob = new Encryption();
  204. $ob->source = "/var/www/bookReservation";
  205. $ob->target = "/var/www/jiami/bookReservation";
  206. // Decrypt the specified file
  207. //$ob->decode('D:\php\WWW\workspace\weixin2\Application\Home\Controller\IndexController.class.php');
  208. //$ob->decode( 'jiami.php');
  209. //$ob->decode('dam6.php');
  210. //Encrypt a specified file directory
  211. $ob->encodeDir($ob->source, $ob->target);
  212. //Decrypt a specified file directory
  213. $ob->decodeDir($ob->target,"/var/www/jiami/bookReservationD");
Copy Code


Encryption and decryption, php


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
PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version