1

I generated a self-siged certificate like so:

openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365

The file cert.pem contains my public key. I wish to extract this public key from this file.
The way I tried to do is:

f = open('cert.pem', "rb")
pem_data = f.read()
f.close()

print(pem_data)
key = serialization.load_pem_public_key(pem_data,  backend=default_backend())

However, after running the code, I get this error:

ValueError: Could not deserialize key data.

As a result I unable to extract the public key.
How do I fix this in order to extract the public key?

Maqruis1
  • 157
  • 1
  • 1
  • 13

2 Answers2

3

Note in the document

A PEM block which starts with -----BEGIN CERTIFICATE----- is not a public or private key, it’s an X.509 Certificate. You can load it using load_pem_x509_certificate() and extract the public key with Certificate.public_key.

Just try this:

from cryptography.hazmat.backends import default_backend
from cryptography import x509

f = open('cert.pem', "rb")
pem_data = f.read()
f.close()

key = x509.load_pem_x509_certificate(pem_data,  backend=default_backend())
public_key = key.public_key()
Chien Nguyen
  • 648
  • 5
  • 7
0

In the first place check cryptography library is installed if it's no like that so:

pip install cryptography

You have to create your RSA keys with OpenSSL:

openssl genrsa -out jwt-key 4096
openssl rsa -in jwt-key -pubout > jwt-key.pub

reference : enter link description here

Javad Asoodeh
  • 299
  • 3
  • 12