search
HomeBackend DevelopmentPHP TutorialExample of php code encryption and decryption class (complete code)

本篇文章给大家带来的内容是关于php代码加密解密类的示例(完整代码) ,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

php 代码加密类,大家可以根据自己的需求进行修改,原类如下,该实例在ubuntu下测试没有问题。

<?php

class Encryption{

    private $c=&#39;&#39;;//存储密文

    private $s=&#39;&#39;,$q1,$q2,$q3,$q4,$q5,$q6;//存储生成的加密后的文件内容

    //如果不设置一个值,isset会表示不存在;

    private $file=&#39;&#39;;//读取文件的路径

    private $source=&#39;&#39;,$target=&#39;&#39;;

    //构造函数,实例化时调用初始化全局变量;

    public function __construct(){

      //初始化全局变量

      $this->initialVar();

      //echo "hello \n";

    }

    /*

    *@input $property_name,$value

    *@output

    *  魔法方法,对变量进行设置值;可根据需求进行处理。若直接去除if判断表示可用设置任何属性的值,包括不存在的属性;

    */

    public function __set($property_name,$value){

      //定义过的变量;

      if(isset($this->$property_name)){

        $this->$property_name = $value;

      }else{

        //异常处理,处理未声明的变量赋值;可根据需求进行处理。

        throw new Exception("property does not exist");

      }

    }

    //魔法方法 取出变量的值;

    public function __get($property_name){

      if(isset($this->$property_name)){

        return $this->$property_name;

      }else{

        //throw new Exception("property does not exist");

        return NULL;

      }

    }

    //取随机排序

    private function RandAbc($length=""){//随机排序取回

     $str="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

     return str_shuffle($str);

    }

    //对明文内容进行加密处理

    private function ciphertext($filename){

      //$filename=&#39;index.php&#39;;

      $T_k1=$this->RandAbc();

      $T_k2=$this->RandAbc();

      $vstr=file_get_contents($filename);

      $v1=base64_encode($vstr);

      $c=strtr($v1,$T_k1,$T_k2);

      $this->c=$T_k1.$T_k2.$c;

      return $this;

    }

    //初始化变量

    private function initialVar(){

      $this->q1="O00O0O";//base64_decode

      $this->q2="O0O000";//$c(原文经过strtr置换后的密文,由 目标字符+替换字符+base64_encode(‘原文内容&#39;)构成)

      $this->q3="O0OO00";//strtr

      $this->q4="OO0O00";//substr

      $this->q5="OO0000";//52

      $this->q6="O00OO0";//urldecode解析过的字符串(n1zb/ma5\vt0i28-pxuqy*6%6Crkdg9_ehcswo4+f37j)

    }

    //生成加密后的模板(复杂版本);

    private function model(){

      //$c = $this->c;

      //$this->initialVar();

      $this->s=&#39;<?php $&#39;.$this->q6.&#39;=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");$&#39;.

      $this->q1.&#39;=$&#39;.$this->q6.&#39;{3}.$&#39;.$this->q6.&#39;{6}.$&#39;.$this->q6.&#39;{33}.$&#39;.$this->q6.&#39;{30};$&#39;.$this->q3.&#39;=$&#39;.$this->q6.&#39;{33}.$&#39;.$this->q6.&#39;{10}.$&#39;

      .$this->q6.&#39;{24}.$&#39;.$this->q6.&#39;{10}.$&#39;.$this->q6.&#39;{24};$&#39;.$this->q4.&#39;=$&#39;.$this->q3.&#39;{0}.$&#39;.$this->q6.&#39;{18}.$&#39;.$this->q6.&#39;{3}.$&#39;.$this->q3.&#39;{0}

      .$&#39;.$this->q3.&#39;{1}.$&#39;.$this->q6.&#39;{24};$&#39;.$this->q5.&#39;=$&#39;.$this->q6.&#39;{7}.$&#39;.$this->q6.&#39;{13};$&#39;.$this->q1.&#39;.=$&#39;.$this->q6.&#39;{22}.$&#39;.$this->q6.&#39;{36}

      .$&#39;.$this->q6.&#39;{29}.$&#39;.$this->q6.&#39;{26}.$&#39;.$this->q6.&#39;{30}.$&#39;.$this->q6.&#39;{32}.$&#39;.$this->q6.&#39;{35}.$&#39;.$this->q6.&#39;{26}.$&#39;.$this->q6.&#39;{30};

      eval($&#39;.$this->q1.&#39;("&#39;.base64_encode(&#39;$&#39;.$this->q2.&#39;="&#39;.$this->c.&#39;";

      eval(\&#39;?>\&#39;.$&#39;.$this->q1.&#39;($&#39;.$this->q3.&#39;($&#39;.$this->q4.&#39;($&#39;.$this->q2.&#39;,$&#39;.$this->q5.&#39;*2),$&#39;.$this->q4.&#39;($&#39;.$this->q2.&#39;,$&#39;.$this->q5.&#39;,$&#39;.$this->q5.&#39;),

      $&#39;.$this->q4.&#39;($&#39;.$this->q2.&#39;,0,$&#39;.$this->q5.&#39;))));&#39;).&#39;"));?>&#39;;

      return $this;

    }

    //创建加密文件

    private function build($target){

      //$this->encodes("./index.php");

      //$this->model();

      $fpp1 = fopen($target,&#39;w&#39;);

      fwrite($fpp1,$this->s) or die(&#39;写入是失败!&#39;);

      fclose($fpp1);

      return $this;

    }

    //加密处理 连贯操作

    public function encode($file,$target){

      //$file = "index.php";

      //连贯操作其实就是利用函数处理完后返回自身

      $this->ciphertext($file)->model()->build($target);

      echo &#39;encode------&#39;.$target.&#39;-----ok<br/>&#39;;

    }

    //解密

    public function decode($file,$target=&#39;&#39;){

      //读取要解密的文件

      $fpp1 = file_get_contents($file);

      $this->decodeMode($fpp1)->build($target);

      echo &#39;decode------&#39;.$target.&#39;-----ok<br/>&#39;;

    }

    //解密模板,得到解密后的文本

    private function decodeMode($fpp1){

      //以eval为标志 截取为数组,前半部分为密文中的替换掉的函数名,后半部分为密文

      $m = explode(&#39;eval&#39;,$fpp1);

      //对系统函数的替换部分进行执行,得到系统变量

      $varStr = substr($m[0],strpos($m[0],&#39;$&#39;));

      //执行后,后续就可以使用替换后的系统函数名

      eval($varStr);

      //判断是否有密文

      if(!isset($m[1])){

        return $this;

      }

      //对密文进行截取 {$this->q4} substr

      $star = strripos($m[1],&#39;(&#39;);

      $end = strpos($m[1],&#39;)&#39;);

      $str = ${$this->q4}($m[1],$star,$end);

      //对密文解密 {$this->q1} base64_decode

      $str = ${$this->q1}($str);

      //截取出解密后的 核心密文

      $evallen = strpos($str,&#39;eval&#39;);

      $str = substr($str,0,$evallen);

      //执行核心密文 使系统变量被赋予值 $O0O000

      eval($str);

      //并不能将如下段封装,因为 ${$this->qn} 并不能在全文中起作用

      $this->s = ${$this->q1}(

        ${$this->q3}(

          ${$this->q4}(

            ${$this->q2},${$this->q5}*2

          ),

          ${$this->q4}(

            ${$this->q2},${$this->q5},${$this->q5}

          ),

          ${$this->q4}(

            ${$this->q2},0,${$this->q5}

          )

        )

      );

      return $this;

    }

    //递归读取并创建目标目录结构

    private function targetDir($target){

      if(!empty($target) ) {

        if(!file_exists($target)){

          mkdir($target,0777,true);

        }else{

          chmod($target,0777);

        }

      }

    }

    //递归解密 对指定文件夹下的php文件解密

    public function decodeDir($source,$target=""){

      if(is_dir($source)){

        $this->targetDir($target);

        $dir = opendir($source);

        while(false!=$file=readdir($dir))

        {

          //列出所有文件并去掉&#39;.&#39;和&#39;..&#39; 此处用的实例为thinkphp框架,所以默认排除里Thinkphp目录,用户可以按照自己的需求设置

          if($file!=&#39;.&#39; && $file!=&#39;..&#39; && $file !=&#39;ThinkPHP&#39;)

          {

            $path = $target.DIRECTORY_SEPARATOR.$file;

            $sourcePath = $source.DIRECTORY_SEPARATOR.$file;

            $this->decodeDir($sourcePath,$path);

          }

        }

      }else if(is_file($source)){

        $extension=substr($source,strrpos($source,&#39;.&#39;)+1);

        if(strtolower($extension)==&#39;php&#39;){

          $this->decode($source,$target);

        }else{

          //不是php的文件不处理

          copy($source, $target);

        }

        //return;

      }

    }

    //递归加密 对指定文件夹下的php文件加密

    public function encodeDir($source,$target){

      if(is_dir($source)){

        $this->targetDir($target);

        $dir = opendir($source);

        while(false!=$file=readdir($dir))

        {

          //列出所有文件并去掉&#39;.&#39;和&#39;..&#39;

          if($file!=&#39;.&#39; && $file!=&#39;..&#39; && $file !=&#39;ThinkPHP&#39;)

          {

            $path = $target.DIRECTORY_SEPARATOR.$file;

            $sourcePath = $source.DIRECTORY_SEPARATOR.$file;

            $this->encodeDir($sourcePath,$path);

          }

        }

      }else if(is_file($source)){

        $extension=substr($source,strrpos($source,&#39;.&#39;)+1);

        if(strtolower($extension)==&#39;php&#39;){

          $this->encode($source,$target);

        }else{

          copy($source, $target);

        }

      }

    }

}

$ob = new Encryption();

$ob->source = "/var/www/bookReservation";

$ob->target = "/var/www/jiami/bookReservation";

//解密指定文件

//$ob->decode(&#39;D:\\php\\WWW\\workspace\\weixin2\\Application\\Home\\Controller\\IndexController.class.php&#39;);

//$ob->decode(&#39;jiami.php&#39;);

//$ob->decode(&#39;dam6.php&#39;);

//对一个指定的文件目录进行加密

$ob->encodeDir($ob->source,$ob->target);

//对一个指定的文件目录进行解密

$ob->decodeDir($ob->target,"/var/www/jiami/bookReservationD");

相关推荐:

加密解密 PHP加密解密类

PHP加密解密函数详解,加密解密函数详解

PHP url 加密解密函数_PHP教程

The above is the detailed content of Example of php code encryption and decryption class (complete 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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

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: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

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 and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

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 and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

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.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

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 and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

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.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

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

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

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.

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

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment