search
HomeBackend DevelopmentPHP Tutorialphp接口数据加密、解密、验证签字代码实例

php接口数据加密、解密、验证签名代码实例

php接口数据加密、解密、验证签名

代码很简单,这里就不多废话了,直接奉上代码

<?php/** * 数据加密,解密,验证签名 * @edit http://www.lai18.com * @date 2015-07-08 **///header('Content-Type: text/xml; charset=utf-8');include_once(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'phpsec'.DIRECTORY_SEPARATOR.'Math'.DIRECTORY_SEPARATOR.'BigInteger.php');include_once(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'phpsec'.DIRECTORY_SEPARATOR.'Crypt'.DIRECTORY_SEPARATOR.'AES.php');include_once(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'phpsec'.DIRECTORY_SEPARATOR.'Crypt'.DIRECTORY_SEPARATOR.'RSA.php');//密文$crypttext = 'v66YKULHFld2JElhm/J9qik2Edr1JHdZIc/k/OesU2GbTX2usXyvF4jGvzvoihrrE8FsfKmllmjsMIjO5fdrS/FD20bYFii4JW3BO3bzshXmz6AEs2DWwG4sK9mNojfOC0IsMoV311X5/JlgUoQXkDy4F5HHpYE9d/xGb0g2XE/hnGSSy2cpQcvQtBlBmixwSckNhsEG92lovlOz8ULwkqG5o7x&#43;qB7P/EMII/WaFAXBJXDXvZX7lmGcOgon6wLhKJLGXorP6BIxOg6LGc6Ux7BAt3i9&#43;0lujNgxIq/sDsl23hsr3yOUpV5C5a813nrHx4HJyd/hBT1UvIUml&#43;eTmJwWCpSfs2cvxIUr0CE57JAZVyXjK13shK3IsZHLPPsm/JcDCrdy0Co/d5uIGJAdzXdsQ56xsju&#43;tlvnA1J6yq2tDIfYK/x6k911A5WXLKYxztD1nq&#43;bTYN3Gv/WFfrzVtgWQBrh06ihS2cwvna0S9EV/YPmhnAjJmrX4trNr9NXQ9xaZaW4lGRg87U5QDV&#43;nQjj1THk0XHFc69N9g2&#43;DsAGyEs9tK6U0ZQ72hJZqZhBCDH1UKw0PLyIhJdxpgPPOWGp8/QVVU2julTeKunvgAAEc3n&#43;GoZfqjsCDi1S6T2MTnjWYWNoFRBhvEZFD/revgpasTOzDQa5NqR1B&#43;mUF70r6uw6MWLJ7cT9Tz3jq&#43;CA';$aeskey = base64_decode('qZe60QZFxuirub2ey4&#43;7&#43;Q==');//AES解密,采用ECB模式$aes = new Crypt_AES(CRYPT_MODE_ECB);//设置AES密钥$aes->setKey($aeskey);//解密AES密文$plaintext = $aes->decrypt(base64_decode($crypttext));echo $plaintext;echo '<hr />';//AES加密明文//echo $aes->encrypt($plaintext);//rsa公钥$publickey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCffOeIVYut9jW5w1L5uKX4aDvd837a8JhaWm5S8YqNQfgEmfD9T&#43;rDknXLqMT&#43;DXeQAqGo4hBmcbej1aoMzn6hIJHk3/TfTAToNN8fgwDotHewsTCBbVkQWtDTby3GouWToVsRi1i/A0Vfb0&#43;xM8MnF46DdhhrnZrycERBSbyrcwIDAQAB';//echo base64_decode($publickey);//rsa签名$signature = 'XHin4uUFqrKDEhKBD/hQisXLFFSxM6EZCvCPqnWCQJq3uEp3ayxmFuUgVE0Xoh4AIWjIIsOWdnaToL1bXvAFKwjCtXnkaRwUpvWrk&#43;Q0eqwsoAdywsVQDEceG5stas1CkPtrznAIW2eBGXCWspOj&#43;aumEAcPyYDxLhDN646Krzw=';//echo base64_decode($signature);$rsa = new Crypt_RSA();//设置RSA签名模式 CRYPT_RSA_SIGNATURE_PSS or CRYPT_RSA_SIGNATURE_PKCS1$rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1);//var_dump($rsa->createKey());//生成RSA公钥、私钥//extract($rsa->createKey());//使用RSA私钥生成签名//$rsa->loadKey($privatekey);//$signature = $rsa->sign($plaintext);//使用RSA公钥验证签名echo $plaintext;$rsa->loadKey(base64_decode($publickey));echo $rsa->verify($plaintext, base64_decode($signature)) ? 'verified' : 'unverified';echo '<hr />';//生成RSA公钥、私钥//var_dump($rsa->createKey());extract($rsa->createKey());//使用RSA私钥加密数据$rsa->loadKey($privatekey);$ciphertext = $rsa->encrypt($plaintext);//使用RSA公钥解密数据$rsa->loadKey($publickey);echo $rsa->decrypt($ciphertext);

每当你讲任何涉及到钱财事务等交易问题时,需要特别注意安全问题的考虑,例如开发一个论坛或者是一个购物车等。

 扩展阅读

《PHP实用问题解决案例》系列技术文章整理收藏 

1PHP汉字拼音转换和公历农历转换

2php购物车实现方法

3PHP实现格式化文件数据大小显示的方法

4PHP+jquery实时显示网站在线人数的方法

5PHP 实现判断用户是否手机访问

6PHP转义Json里的特殊字符的函数

7php基于socket实现SMTP发送邮件的方法

8PHP查询快递信息的方法

9PHP简单获取视频预览图的方法

10php接口数据加密、解密、验证签名

11php计算指定目录下文件占用空间的方法

12php通过递归方式复制目录和子目录的方法

13php中通过DirectoryIterator删除整个目录的方法

14PHP生成迅雷、快车、旋风等软件的下载链接代码实例

15PHP中文乱码分类及解决办法大全

16php从数组中随机选择若干不重复元素的方法

17PHP文件上传问题总结——文件大小检测以及大文件上传处理

18如何修改PHP的memory_limit限制

19php判断一个请求是ajax请求还是普通请求的方法

20PHP超牛逼无限极分类生成树方法

21长微博生成(将html转化为图片)原理浅析

版权声明:本文为博主原创文章,未经博主允许不得转载。

1楼qq2291738886昨天 20:51
2291738886
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
What is dependency injection in PHP?What is dependency injection in PHP?May 07, 2025 pm 03:09 PM

DependencyinjectioninPHPisadesignpatternthatenhancesflexibility,testability,andmaintainabilitybyprovidingexternaldependenciestoclasses.Itallowsforloosecoupling,easiertestingthroughmocking,andmodulardesign,butrequirescarefulstructuringtoavoidover-inje

Best PHP Performance Optimization TechniquesBest PHP Performance Optimization TechniquesMay 07, 2025 pm 03:05 PM

PHP performance optimization can be achieved through the following steps: 1) use require_once or include_once on the top of the script to reduce the number of file loads; 2) use preprocessing statements and batch processing to reduce the number of database queries; 3) configure OPcache for opcode cache; 4) enable and configure PHP-FPM optimization process management; 5) use CDN to distribute static resources; 6) use Xdebug or Blackfire for code performance analysis; 7) select efficient data structures such as arrays; 8) write modular code for optimization execution.

PHP Performance Optimization: Using Opcode CachingPHP Performance Optimization: Using Opcode CachingMay 07, 2025 pm 02:49 PM

OpcodecachingsignificantlyimprovesPHPperformancebycachingcompiledcode,reducingserverloadandresponsetimes.1)ItstorescompiledPHPcodeinmemory,bypassingparsingandcompiling.2)UseOPcachebysettingparametersinphp.ini,likememoryconsumptionandscriptlimits.3)Ad

PHP Dependency Injection: Boost Code MaintainabilityPHP Dependency Injection: Boost Code MaintainabilityMay 07, 2025 pm 02:37 PM

Dependency injection provides object dependencies through external injection in PHP, improving the maintainability and flexibility of the code. Its implementation methods include: 1. Constructor injection, 2. Set value injection, 3. Interface injection. Using dependency injection can decouple, improve testability and flexibility, but attention should be paid to the possibility of increasing complexity and performance overhead.

How to Implement Dependency Injection in PHPHow to Implement Dependency Injection in PHPMay 07, 2025 pm 02:33 PM

Implementing dependency injection (DI) in PHP can be done by manual injection or using DI containers. 1) Manual injection passes dependencies through constructors, such as the UserService class injecting Logger. 2) Use DI containers to automatically manage dependencies, such as the Container class to manage Logger and UserService. Implementing DI can improve code flexibility and testability, but you need to pay attention to traps such as overinjection and service locator anti-mode.

What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

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

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

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.