如何使用Python/GoLang操作PDF电子签名?编码实现PDF数字签名的最简方式及Python/GoLang指南需求
Hey there! Let's break down how to work with digitally signed PDFs (both reading/verifying existing ones and adding new signatures) using Python or Go—here's what I've found works best for quick, reliable implementations:
1. 操作已有的带电子签名PDF
If you just need to read signature metadata or run basic verification checks, PyPDF2 is a lightweight, easy-to-go option. It lets you pull key signature details with minimal code:
from PyPDF2 import PdfReader # 读取带签名的PDF文件 reader = PdfReader("signed_document.pdf") # 遍历并输出所有签名信息 for signature in reader.signatures: print(f"签名者名称: {signature.name}") print(f"签名时间: {signature.signing_time}") # 执行基础签名验证 is_valid = signature.verify() print(f"签名是否通过验证: {is_valid}\n")
Note: For advanced verification (like checking certificate chains or revocation status), pair this with the cryptography library or use a specialized tool like pyhanko.
2. 给PDF添加数字签名(最简方式)
The simplest way to add a digital signature in Python is using pyhanko—it abstracts away most low-level PDF signature logic and works seamlessly with both self-signed and CA-issued certificates.
First, install the required packages:
pip install pyhanko pyhanko-certvalidator
Generate a self-signed certificate for testing (via OpenSSL):
openssl req -x509 -newkey rsa:4096 -keyout private_key.pem -out cert.pem -days 365 -nodes
Then use this code to sign your PDF:
from pyhanko import sign from pyhanko.pdf_utils.incremental_writer import IncrementalPdfFileWriter # 打开原始PDF并创建增量写入器(保留原始内容) with open("input.pdf", "rb") as in_file, open("signed_output.pdf", "wb") as out_file: writer = IncrementalPdfFileWriter(in_file) # 加载签名密钥和证书 signer = sign.SimpleSigner.load( cert_file="cert.pem", key_file="private_key.pem" ) # 执行签名,设置签名框位置和显示文本 sign.sign_pdf( writer, signers=signer, appearance=sign.PdfSignatureAppearance( signature_box=(100, 100, 300, 150), # 格式:(x1, y1, x2, y2) text="Signed by [Your Name]", font_size=12 ) ) # 写入签名后的PDF writer.write(out_file)
For production use, replace the self-signed certificate with one issued by a trusted CA to ensure your signatures are universally verifiable.
1. 操作已有的带电子签名PDF
In Go, pdfcpu is a robust library that handles PDF signature reading and verification with clean, straightforward APIs. Here's how to extract and validate signatures:
First, install the dependency:
go get github.com/pdfcpu/pdfcpu/pkg/api
Then use this code:
package main import ( "fmt" "github.com/pdfcpu/pdfcpu/pkg/api" "github.com/pdfcpu/pdfcpu/pkg/pdfcpu" ) func main() { // 创建PDF处理上下文 ctx, err := api.ReadContextFile("signed_document.pdf", pdfcpu.NewDefaultConfiguration()) if err != nil { panic(err) } // 获取所有签名信息 signatures, err := ctx.Signatures() if err != nil { panic(err) } for _, sig := range signatures { fmt.Printf("签名ID: %s\n", sig.ID) fmt.Printf("签名者: %s\n", sig.Name) fmt.Printf("签名时间: %s\n", sig.CreationDate.Format("2006-01-02 15:04:05")) // 验证签名有效性 isValid, err := sig.Verify(ctx) if err != nil { panic(err) } fmt.Printf("签名是否有效: %t\n\n", isValid) } }
2. 给PDF添加数字签名(最简方式)
pdfcpu also simplifies the signing process in Go. You'll need a private key and certificate (generate with OpenSSL as before), then use this code:
package main import ( "github.com/pdfcpu/pdfcpu/pkg/api" "github.com/pdfcpu/pdfcpu/pkg/pdfcpu" ) func main() { // 配置签名参数 signConfig := pdfcpu.SignConfig{ KeyFile: "private_key.pem", CertFile: "cert.pem", Reason: "Document authentication", Location: "Shanghai", ContactInfo: "support@example.com", Rect: []float64{100, 100, 300, 150}, // 签名框位置 Page: 1, // 签名在第1页 } // 执行签名 err := api.SignFile("input.pdf", "signed_output.pdf", signConfig, pdfcpu.NewDefaultConfiguration()) if err != nil { panic(err) } fmt.Println("PDF successfully signed!") }
Quick reminder: Always use CA-issued certificates for production signatures—self-signed ones are only suitable for testing, as they won't be trusted by external parties.
内容的提问来源于stack exchange,提问作者Anindya




