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

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同时传输传输。

http://www.xdnf.cn/news/10155.html

相关文章:

  • 【leetcode】02.07. 链表相交
  • 大模型-attention汇总解析之-MLA
  • 循序渐进PersistentVolumes与PersistentVolumeClaim
  • shell管道笔记
  • Oralce RAC DRM详解
  • 【征求意见】四川省大数据发展研究会关于对《数据资源建设费用测算标准》团体标准征求意见的通知
  • Python_day40
  • Python常见的面试题
  • vueflow
  • 【仿生机器人】需求案例
  • EWM108-GN06B系列BDS单北斗卫星定位模块产品简介
  • [IMX] 10.串行外围设备接口 - SPI
  • win32相关(创建线程)
  • 多线程(3)
  • MySQL中怎么看是否走了索引
  • 数据库中求最小函数依赖集-最后附解题过程
  • EMQX服务
  • DALI DT6与DALI DT8介绍
  • PlankAssembly 笔记 DeepWiki 正交视图三维重建
  • redis缓存与数据库协调读写机制设计
  • JAVA 集合进阶 泛型类、泛型方法、泛型接口
  • 【算法训练营Day03】链表part1
  • 随笔笔记记录5.28
  • 说一说SAP系统从Non-Unicode到Unicode的演化
  • 674SJBH校园外卖订餐系统V3
  • OpenLayers 图形绘制
  • 卫星地图 App 的实测体验深度解析
  • DeepSeek 赋能工业互联网:设备预测性维护的智能革新之路
  • 突破铁芯CT局限:罗氏线圈的“无磁饱和”技术深度解读
  • 身份证信息OCR识别提取