Reputation: 19
I have created a certificate with Adobe Reader and saved it to the hard disk. Now, I would like to extract the PEM key in order to create a digital signature for other PDF files using a different program not mentioned here
import PyPDF2
from cryptography import x509
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.hashes import SHA256
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.serialization.pkcs12 import load_key_and_certificates
def pfxToPem():
# Load the pfx file
certificato_pfx = 'Nome.pfx'
password = 'aaaaa'
with open(certificato_pfx, 'rb') as pfx_file:
pfx_data = pfx_file.read()
# Extracts key and certificate
private_key, certificate, additional_certificates = load_key_and_certificates(pfx_data, password.encode('utf-8'))
# Serialize key
private_key_pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
)
# Save to file
with open('chiave.pem', 'wb') as key_file:
key_file.write(private_key_pem)
return message :
CryptographyDeprecationWarning: Parsed a negative serial number, which is disallowed by RFC 5280.
Is there an error in the code?
Why am I receiving this message even though the certificate was created by a reputable software like Adobe ?
Do I need to manually change the serial number?
Thank you
Upvotes: 1
Views: 1641
Reputation: 4741
Maybe something like this might be useful.
from cryptography.hazmat.primitives.serialization import pkcs12, Encoding, PrivateFormat, NoEncryption
with open('Nome.pfx', 'rb') as in_file:
pfx = pkcs12.load_pkcs12(in_file.read(), b'aaaaa')
pvt = pfx.key.private_bytes(Encoding.PEM, PrivateFormat.TraditionalOpenSSL, NoEncryption())
cert = pfx.cert.certificate.public_bytes(Encoding.PEM)
if pfx.additional_certs:
for _cert in a.additional_certs:
_cert.certificate.public_bytes(Encoding.PEM)
You can either write the key and certificate to a file to use the loaded key for further use.
Upvotes: 2