You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PHP实现类似OpenSSL CMS命令的API请求数字签名?

使用phpseclib实现与OpenSSL CMS命令一致的签名结果

你需要用phpseclib 3.x版本实现对应OpenSSL命令的功能,以下是代码实现,每一步都对应原命令的参数:

<?php
require 'vendor/autoload.php';

use phpseclib3\File\X509;
use phpseclib3\Crypt\RSA;
use phpseclib3\File\CMS;

// 加载签名证书与私钥
$cert = new X509();
$cert->loadX509(file_get_contents('my.crt'));

$privateKey = RSA::loadPrivateKey(file_get_contents('my.key'));
// 若私钥带密码,改为:RSA::loadPrivateKey(file_get_contents('my.key'), '你的密码');

// 读取待签名的内容(对应原命令的digest.txt)
$content = file_get_contents('digest.txt');

// 初始化CMS签名器并配置参数
$cms = new CMS();
$cms->setSigner($cert, $privateKey);
$cms->setContent($content);

// 对应 -noattr:移除签名时间、内容类型等属性
$cms->setAttribute(CMS::ATTR_SIGNING_TIME, false);
$cms->setAttribute(CMS::ATTR_CONTENT_TYPE, false);
// 对应 -nosmimecap:移除SMIME算法支持列表属性
$cms->setAttribute(CMS::ATTR_SMIMECAP, false);
// 对应 -nocerts:不将签名者证书包含进结果
$cms->includeCertificates(false);
// 对应 -binary:按二进制格式处理内容,不转换换行符
$cms->setBinaryMode(true);

// 生成DER格式签名(对应 -outform der)
$signature = $cms->sign(CMS::FORMAT_DER);

// $signature 即为与OpenSSL命令输出完全一致的二进制签名内容
// 如需保存到文件可执行:file_put_contents('digest.sign', $signature);
?>

参数对应说明

  • setSigner($cert, $privateKey) → 对应原命令的 -signer my.crt -inkey my.key
  • setContent($content) → 对应 -in digest.txt
  • 各类setAttribute(..., false) → 对应 -noattr 和 -nosmimecap
  • includeCertificates(false) → 对应 -nocerts
  • setBinaryMode(true) → 对应 -binary
  • sign(CMS::FORMAT_DER) → 对应 -outform der

前置要求

确保已通过Composer安装phpseclib:

composer require phpseclib/phpseclib

内容的提问来源于stack exchange,提问作者IronSide

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 01:04:55