search
HomeBackend DevelopmentPHP TutorialWhen decoding the applet, the mcrypt extension cannot be used in PHP 7.0 or above. The old version of the decryption solution

The content shared with you in this article is that the mcrypt extension of PHP 7.0 or above cannot use the old version of the decryption solution when decoding the mini program. It has a certain reference value. Friends in need can refer to it

<br/>
WXBizDataCrypt.php
class	WXBizDataCrypt	{

				private	$appid;
				private	$sessionKey;

				/**
					* 构造函数
					* @param $sessionKey string 用户在小程序登录后获取的会话密钥
					* @param $appid string 小程序的appid
					*/
				public	function	__construct($appid,	$sessionKey)	{
						$this->sessionKey	=	$sessionKey;
						$this->appid	=	$appid;
				}

				/**
					* 检验数据的真实性,并且获取解密后的明文.
					* @param $encryptedData string 加密的用户数据
					* @param $iv string 与用户数据一同返回的初始向量
					* @param $data string 解密后的原文
					*
					* @return int 成功0,失败返回对应的错误码
					*/
				public	function	decryptData($encryptedData,	$iv,	&$data)	{
						if	(strlen($this->sessionKey)	!=	24)	{
								return	ErrorCode::$IllegalAesKey;
						}
						$aesKey	=	base64_decode($this->sessionKey);


						if	(strlen($iv)	!=	24)	{
								return	ErrorCode::$IllegalIv;
						}
						$aesIV	=	base64_decode($iv);

						$aesCipher	=	base64_decode($encryptedData);

						$pc	=	new	Prpcrypt($aesKey);
						$result	=	$pc->decrypt($aesCipher,	$aesIV);

						if	($result[0]	!=	0)	{
								return	$result[0];
						}

						$dataObj	=	json_decode($result[1]);
						if	($dataObj	==	NULL)	{
								return	ErrorCode::$IllegalBuffer;
						}
						if	($dataObj->watermark->appid	!=	$this->appid)	{
								return	ErrorCode::$IllegalBuffer;
						}
						$data	=	$result[1];
						return	ErrorCode::$OK;
				}
			// 	// 注释这一段是7.0以上版本
			// public function decryptData( $encryptedData, $iv, &$data )
			//     {
			//         if (strlen($this->sessionKey) != 24) {
			//             return ErrorCode::$IllegalAesKey;
			//         }
			//         $aesKey=base64_decode($this->sessionKey);
			        
			//         if (strlen($iv) != 24) {
			//             return ErrorCode::$IllegalIv;
			//         }
			//         $aesIV=base64_decode($iv);
			//         // $aesCipher=base64_decode($encryptedData);
			//         $aesCipher=$encryptedData;
			//         $pc = new Prpcrypt($aesKey);
			//         $result = $pc->decrypt($aesCipher,$aesIV);
			//      //   var_dump($result);
			//         if ($result[0] != 0) {
			//             return $result[0];
			//         }
			     
			//         $dataObj=json_decode( $result[1] );
			//         if( $dataObj  == NULL )
			//         {
			//             return ErrorCode::$IllegalBuffer.&#39;--&#39;;
			//         }
			//         if( $dataObj->watermark->appid != $this->appid )
			//         {
			//             return ErrorCode::$IllegalBuffer.&#39;;;&#39;;
			//         }
			//         $data = $result[1];
			//         return ErrorCode::$OK;
			//     }

		}



PKCS7Encoder.php


##

		class	PKCS7Encoder	{

				public	static	$block_size	=	16;

				/**
					* 对需要加密的明文进行填充补位
					* @param $text 需要进行填充补位操作的明文
					* @return 补齐明文字符串
					*/
				function	encode($text)	{
						$block_size	=	PKCS7Encoder::$block_size;
						$text_length	=	strlen($text);
						//计算需要填充的位数
						$amount_to_pad	=	PKCS7Encoder::$block_size	-	(	$text_length	%	PKCS7Encoder::$block_size	);
						if	($amount_to_pad	==	0)	{
								$amount_to_pad	=	PKCS7Encoder::block_size;
						}
						//获得补位所用的字符
						$pad_chr	=	chr($amount_to_pad);
						$tmp	=	"";
						for	($index	=	0;	$index	<	$amount_to_pad;	$index++)	{
								$tmp	.=	$pad_chr;
						}
						return	$text	.	$tmp;
				}

				/**
					* 对解密后的明文进行补位删除
					* @param decrypted 解密后的明文
					* @return 删除填充补位后的明文
					*/
				function	decode($text)	{

						$pad	=	ord(substr($text,	-1));
						if	($pad	<	1	||	$pad	>	32)	{
								$pad	=	0;
						}
						return	substr($text,	0,	(strlen($text)	-	$pad));
				}

		}

		/**
			* Prpcrypt class
			*
			* 
			*/
		class	Prpcrypt	{

				public	$key;

				public	function	__construct($k)	{
						$this->key	=	$k;
				}

				/**
					* 对密文进行解密
					* @param string $aesCipher 需要解密的密文
					* @param string $aesIV 解密的初始向量
					* @return string 解密得到的明文
					*/
				public	function	decrypt($aesCipher,	$aesIV)	{

						try	{

								$module	=	mcrypt_module_open(MCRYPT_RIJNDAEL_128,	&#39;&#39;,	MCRYPT_MODE_CBC,	&#39;&#39;);

								mcrypt_generic_init($module,	$this->key,	$aesIV);

								//解密
								$decrypted	=	mdecrypt_generic($module,	$aesCipher);
								mcrypt_generic_deinit($module);
								mcrypt_module_close($module);
						}	catch	(Exception	$e)	{
								return	array(ErrorCode::$IllegalBuffer,	null);
						}


						try	{
								//去除补位字符
								$pkc_encoder	=	new	PKCS7Encoder;
								$result	=	$pkc_encoder->decode($decrypted);
						}	catch	(Exception	$e)	{
								//print $e;
								return	array(ErrorCode::$IllegalBuffer,	null);
						}
						return	array(0,	$result);
				}

                                  //php 7.0版本
				 // public function decrypt( $aesCipher, $aesIV )
				 //    {
				 //        try {
				            
				 //            // $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, &#39;&#39;, MCRYPT_MODE_CBC, &#39;&#39;);
				            
				 //            // mcrypt_generic_init($module, $this->key, $aesIV);
				 //            // //解密
				 //            // $decrypted = mdecrypt_generic($module, $aesCipher);
				 //            // mcrypt_generic_deinit($module);
				 //            // mcrypt_module_close($module);
				 //            $decrypted = openssl_decrypt($aesCipher,&#39;AES-128-CBC&#39;,$this->key,OPENSSL_ZERO_PADDING,$aesIV);
				 //            // var_dump($decrypted);
				 //        } catch (Exception $e) {
				 //            return array(ErrorCode::$IllegalBuffer, null);
				 //        }
				 //        try {
				 //            //去除补位字符
				 //            $pkc_encoder = new PKCS7Encoder;
				 //            $result = $pkc_encoder->decode($decrypted);
				 //        } catch (Exception $e) {
				 //            //print $e;
				 //            return array(ErrorCode::$IllegalBuffer, null);
				 //        }
				 //        return array(0, $result);
				 //    }

		}




The above is the detailed content of When decoding the applet, the mcrypt extension cannot be used in PHP 7.0 or above. The old version of the decryption solution. 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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

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 Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

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.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.