php实现电子签章
实现电子签章的基本流程
电子签章通常涉及数字签名、证书验证和文档处理。以下是PHP实现电子签章的核心步骤:
生成或获取数字证书 使用OpenSSL扩展生成密钥对和证书,或从合法CA机构获取商用证书。示例代码生成自签名证书:
$config = array(
"digest_alg" => "sha512",
"private_key_bits" => 4096,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
);
$res = openssl_pkey_new($config);
openssl_pkey_export($res, $privateKey);
$csr = openssl_csr_new($config, $res);
$x509 = openssl_csr_sign($csr, null, $res, 365);
openssl_x509_export($x509, $publicKey);
文档哈希处理
对需要签章的文档进行哈希运算,确保数据完整性:

$document = file_get_contents('contract.pdf');
$hash = hash('sha256', $document);
生成数字签名
使用私钥对文档哈希进行加密生成签名:
openssl_sign($hash, $signature, $privateKey, OPENSSL_ALGO_SHA256);
$signatureBase64 = base64_encode($signature);
验证签名
接收方使用公钥验证签名有效性:

$isValid = openssl_verify($hash, base64_decode($signatureBase64), $publicKey, OPENSSL_ALGO_SHA256);
if ($isValid === 1) {
echo "签名验证成功";
} else {
echo "签名验证失败";
}
可视化签章实现
将签名信息与图像结合生成可视化电子印章:
$stampImage = imagecreatefrompng('stamp_template.png');
$color = imagecolorallocate($stampImage, 255, 0, 0);
imagettftext($stampImage, 12, 0, 50, 50, $color, 'arial.ttf', '电子签章');
imagepng($stampImage, 'signed_stamp.png');
imagedestroy($stampImage);
时间戳服务集成
为签章添加可信时间戳:
$tsaUrl = 'https://timestamp.example.org';
$tsQuery = http_build_query(['hash' => $hash]);
$timestamp = file_get_contents($tsaUrl . '?' . $tsQuery);
完整签章文档生成
将签名信息嵌入PDF文档(需使用TCPDF或FPDI库):
require_once('tcpdf/tcpdf.php');
$pdf = new TCPDF();
$pdf->AddPage();
$pdf->Image('signed_stamp.png', 150, 200, 40);
$pdf->SetFont('helvetica', '', 10);
$pdf->Text(150, 240, "签名验证码: " . substr($signatureBase64, 0, 16));
$pdf->Output('signed_contract.pdf', 'D');
注意事项
- 生产环境应使用正规CA颁发的数字证书
- 敏感操作需在HTTPS环境下进行
- 私钥必须安全存储,建议使用硬件加密模块
- 考虑符合当地电子签名法律法规要求
- 重要文档建议配合区块链存证技术
以上实现方案可根据具体需求进行调整,复杂场景建议使用专业电子签章SaaS服务或SDK。



