I am creating a Django app to verify PDF digital signatures, commonly used in Indian government IDs like Aadhaar, ration cards, and tender documents. However, I am unsure how to verify these digital signatures using Python.
Can anyone guide me on how to achieve this? Any libraries or code examples would be greatly appreciated.
Thanks in advance!
1
1. Install Required Libraries
pip install PyPDF2 cryptography pikepdf
2. Basic Verification with 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. Advanced Verification with 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. Using Cryptography Library
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}")
-
Third-party Libraries/Tools
pip install pyhanko
Example: from pyhanko.sign.validation import validate_pdf_signaturewith open(“signed_document.pdf”, “rb”) as doc:
validation_results = validate_pdf_signature(doc)for res in validation_results:
print(res)
zainraza95 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1