Reputation: 13
I'm trying to import a user's certificate from an SQLite database instead of using an actual file, but I'm encountering issues when attempting to use it with the pyhanko library for signing a PDF.
Here is my pdf-signer.py code, which implements a simple PDF signing process:
import sqlite3
from pyhanko.pdf_utils.incremental_writer import IncrementalPdfFileWriter
from pyhanko.sign import signers, timestamps
from pyhanko.sign.fields import SigSeedSubFilter
from pyhanko_certvalidator import ValidationContext
from pyhanko.keys import load_cert_from_pemder, load_certs_from_pemder_data, load_certs_from_pemder
with sqlite3.connect("pki.db") as conn:
cursor = conn.cursor()
cursor.execute("SELECT certificate FROM Users WHERE username=?", ('alice',))
result = cursor.fetchone()
certificate_pem = result[0]
certificate_bytes = certificate_pem.encode("utf-8")
certs = list(load_certs_from_pemder_data(certificate_bytes))
user_cert = certs[0]
# Create the signer
signer = signers.SimpleSigner.load(
cert_file=user_cert,
key_file='key.pem'
)
root_cert = load_cert_from_pemder('rootca_cert.pem')
# FREE-TSA time stamper
timestamper = timestamps.HTTPTimeStamper(
url='https://freetsa.org/tsr'
)
freetsa_root_cert = load_cert_from_pemder('tsa.crt')
signature_meta = signers.PdfSignatureMetadata(
field_name='Signature', md_algorithm='sha256',
subfilter=SigSeedSubFilter.PADES,
validation_context=ValidationContext(
allow_fetching=True,
trust_roots=[root_cert, freetsa_root_cert]
),
embed_validation_info=True,
use_pades_lta=True
)
with open('input.pdf', 'rb') as inf:
w = IncrementalPdfFileWriter(inf)
with open('output.pdf', 'wb') as outf:
signers.sign_pdf(
w,
signature_meta=signature_meta,
signer=signer,
timestamper=timestamper,
output=outf
)
The SimpleSigner.load() method expects a certificate file path (cert_file), but I'm trying to pass a certificate loaded from the database as a variable. How can I correctly load and use the in-memory certificate for signing? I have tried loading data as bytes from the db with (load_certs_from_pemder_data(certificate_bytes)) and other methods but i keep getting the error : Could not load cryptographic material ,AttributeError: 'NoneType' object has no attribute 'get_signature_mechanism_for_digest'
Upvotes: 0
Views: 17