我正在创建一个 Django 应用程序来验证 PDF 数字签名,通常用于印度政府 ID,如 Aadhaar、配给卡和招标文件。但是,我不确定如何使用 Python 验证这些数字签名。
任何人都可以指导我如何实现这一目标吗?任何库或代码示例将不胜感激。
提前致谢!
1。安装所需的库
pip install PyPDF2 cryptography pikepdf
2。使用 PyPDF2 进行基本验证
from PyPDF2 import PdfReader
# Load the PDF
file_path = "signed_document.pdf"
reader = PdfReader(file_path)
# Check for signature fields
fields = reader.get_fields()
if fields:
print("Fields detected:")
for field_name, field_data in fields.items():
print(f"Field: {field_name}, Data: {field_data}")
else:
print("No signature fields detected.")
3。使用 PdfSig 进行高级验证
sudo apt install poppler-utils
import subprocess
file_path = "signed_document.pdf"
# Run pdfsig command
result = subprocess.run(["pdfsig", file_path], capture_output=True, text=True)
# Output the verification results
if result.returncode == 0:
print("Verification Details:")
print(result.stdout)
else:
print("Error verifying signature.")
print(result.stderr)
4。使用密码学库
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.serialization import load_pem_public_key
# Example of signature and public key (you must extract these from the PDF)
signature = b"..."
public_key_data = b"""-----BEGIN PUBLIC KEY-----
...
-----END PUBLIC KEY-----"""
message = b"original_message_to_verify" # Extract the exact signed data
# Load public key
public_key = load_pem_public_key(public_key_data)
# Verify signature
try:
public_key.verify(
signature,
message,
padding.PKCS1v15(),
hashes.SHA256()
)
print("Signature is valid.")
except Exception as e:
print(f"Signature verification failed: {e}")
第三方库/工具
pip 安装 pyhanko 示例:从 pyhanko.sign.validation 导入 validate_pdf_signature
以 open("signed_document.pdf", "rb") 作为文档: 验证结果 = validate_pdf_signature(doc)
validation_results 中的资源: 打印(res)