php实现电子签章
PHP实现电子签章的基本方法
电子签章通常涉及数字签名、图像处理和PDF操作。以下是实现电子签章的核心步骤:
生成数字签名
使用PHP的OpenSSL扩展生成数字签名:
$privateKey = openssl_pkey_get_private("file://path/to/private.key");
$data = "需要签名的内容";
openssl_sign($data, $signature, $privateKey, OPENSSL_ALGO_SHA256);
$signatureBase64 = base64_encode($signature);
创建签章图像
使用GD库或Imagick创建签章图像:
$image = imagecreatetruecolor(200, 100);
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefilledrectangle($image, 0, 0, 199, 99, $bgColor);
$textColor = imagecolorallocate($image, 0, 0, 255);
imagettftext($image, 20, 0, 10, 50, $textColor, 'path/to/font.ttf', '电子签章');
imagepng($image, 'signature.png');
imagedestroy($image);
集成PDF签章
使用TCPDF或FPDI库在PDF中添加签章:
require_once('tcpdf/tcpdf.php');
$pdf = new TCPDF();
$pdf->AddPage();
$pdf->Image('signature.png', 10, 10, 40, 20);
$pdf->Output('document.pdf', 'F');
验证签名
验证签名的有效性:
$publicKey = openssl_pkey_get_public("file://path/to/public.key");
$isValid = openssl_verify($data, $signature, $publicKey, OPENSSL_ALGO_SHA256);
if ($isValid === 1) {
echo "签名有效";
}
安全存储
将签章信息安全存储到数据库:
$stmt = $pdo->prepare("INSERT INTO signatures (user_id, signature_data, timestamp) VALUES (?, ?, ?)");
$stmt->execute([$userId, $signatureBase64, time()]);
时间戳服务
集成可信时间戳服务:
$timestampUrl = "https://timestamp.example.com/api";
$timestampData = file_get_contents($timestampUrl.'?hash='.sha1($signatureBase64));
以上方法提供了电子签章的基本实现框架,实际应用中需要根据具体需求调整安全策略和业务流程。






