当前位置: 首页 > news >正文

PHP下实现RSA的加密,解密,加签和验签

前言:

RSA下加密,解密,加签和验签是四种不同的操作,有时候会搞错,记录一下。

1.公钥加密,私钥解密

发送方通过公钥将原数据加密成一个sign参数,相当于就是信息的载体,接收方能通过sign解密出原数据

/*** 公钥加密*/public static function encrypt($string,$type,$params=[]):string{try{$params['act'] = $params['act']??[];$publicKey = file_get_contents( app()->getRootPath() . "storage/resource/{$type}/public_key.pem");openssl_public_encrypt($string, $encrypted, $publicKey);$encrypted = base64_encode($encrypted);if(in_array('rawurlencode',$params['act'])){$encrypted = rawurlencode($encrypted);}return $encrypted;} catch (\Exception $e) {throw new \Exception($e->getMessage());}/*** 私钥解密*/public static function decrypt($string,$type,$params=[]):string{try{$params['act'] = $params['act']??[];$privateKeyContent = file_get_contents( app()->getRootPath() . "storage/resource/{$type}/private_key.pem");$privateKey = openssl_pkey_get_private([$privateKeyContent,$params['password'],]);if ($privateKey === false) {throw new \Exception('私钥加载失败:' . openssl_error_string());}// 4. 解密数据$string = base64_decode($string);if(in_array('rawurldecode',$params['act'])){$string = rawurldecode($string);}$decryptSuccess = openssl_private_decrypt($string, $decryptedData, $privateKey);if (!$decryptSuccess) {throw new \Exception('解密失败:' . openssl_error_string());}//释放内存openssl_free_key($privateKey);return $decryptedData;} catch (\Exception $e) {throw new \Exception($e->getMessage());}}
使用

1.第三方向本站发送数据,先将公钥同步给第三方。
2.第三方将 name=xiaozhao&age=20 用公钥直接加密成sign参数。
3.第三方将sign发送给我站。
4.我站用私钥将xxx重新解密成 name=xiaozhao&age=20。
4.原数据加密为sign状态下传输。

2.私钥加签,公钥验签

我方和接收方事先协商好加签规则,然后将原数据生成一个sign参数,接收方将一起带来的原数据跟sign参数对比,看是否一致。

 /*** 私钥加签*/public static function sign($string, $type,$params=[]){try {$privateKeyContent = file_get_contents( app()->getRootPath() . "storage/resource/{$type}/private_key.pem");$privateKey = openssl_pkey_get_private([$privateKeyContent,$params['password'],]);if ($privateKey === false) {throw new \Exception('私钥加载失败:' . openssl_error_string());}// 4. 创建签名$signature = '';if (!openssl_sign($string, $signature, $privateKey, OPENSSL_ALGO_SHA256)) {throw new \Exception('签名创建失败: ' . openssl_error_string());}// 5. 返回Base64编码的签名return base64_encode($signature);} catch (\Exception $e) {throw new \Exception("签名过程中发生错误: " . $e->getMessage());}}/*** 公钥验签*/public static function verify($string, $type, $sign) {try {$publicKeyContent = file_get_contents(app()->getRootPath() . "storage/resource/{$type}/public_key.pem");// 关键修复:解析公钥为 OpenSSL 资源$publicKey = openssl_pkey_get_public($publicKeyContent);if ($publicKey === false) {throw new \Exception('公钥加载失败: ' . openssl_error_string());}// 清理签名数据$sign = base64_decode(trim(str_replace(["\r", "\n", " "], '', $sign)));$result = openssl_verify($string, $sign, $publicKey, OPENSSL_ALGO_SHA256);// 释放密钥资源openssl_free_key($publicKey);if ($result === -1) {throw new \Exception('参数无效或密钥格式错误: ' . openssl_error_string());}if ($result === 0) {throw new \Exception('验证失败');}return $result === 1;} catch (\Exception $e) {throw new \Exception("验签失败: " . $e->getMessage());}}
使用

密钥 MIGfMA0G 开头的是PKCS#1 格式,MIIBIjANBgkqh 开头的是PKCS#8 格式。PKCS#8格式提取公钥的时候要先用openssl_pkey_get_public提取

1.本站向第三方发送数据,先将公钥发给第三方。
2.我站将 name=xiaozhao&age=20用双方协商好的方式排序(如去掉空数据,再按键名排序等)后,用私钥生成签名sign。
3.我站将原数据和sign一起发送给我站。
3.第三方将原参数用双方协商好的方式排序后,和sign参数用公钥验签
4.原数据和sign同时传输传输。

相关文章:

  • 进程间通信(信号量)
  • 山东大学软件学院项目实训-基于大模型的模拟面试系统-面试官和面试记录的分享功能(2)
  • Aviator复习
  • 【快速解决】数据库快速导出成sql文件
  • 【Netty系列】实现HTTP文件服务器
  • 【Kotlin】简介变量类接口
  • AI预测3D新模型百十个定位预测+胆码预测+去和尾2025年5月31日第94弹
  • [9-3] 串口发送串口发送+接收 江协科技学习笔记(26个知识点)
  • Kafka 如何保证不重复消费
  • C++中 newdelete 与 mallocfree 的异同详解
  • Matlab数据类型
  • Redis7底层数据结构解析
  • Redis:功能特性和应用场景
  • c++ typeid运算符
  • [Windows] Dism++_Mod系统清理优化利器v10.1.1002.1B绿色魔改版
  • 【Redis技术进阶之路】「原理分析系列开篇」分析客户端和服务端网络诵信交互实现(服务端执行命令请求的过程 - 文件事件处理部分)
  • 大数据运维过程中常见的一些操作
  • 【Dv3Admin】工具分页配置文件解析
  • TomatoSCI分析日记:数据分析为什么用csv不用excel
  • javaScirpt学习第五章(函数)-第二部分
  • 南京做网站多少钱/怎么开发自己的网站
  • 大型门户网站的建设外包在本公司制作好还是/seo怎么收费的
  • 学生个人网站制作软件/中国网络优化公司排名
  • 山东省菏泽市城乡建设局网站/营销策略有哪些方法
  • 做外贸需要关注的网站有什么问题/seo综合优化公司
  • 织梦网站数据库备份文件夹/莆田关键词优化报价