how convert a public key from string type to PEM

Viewed 1091

I have a problem and I want some help. I need to send a message from sender to receiver, and this message content signed data and public key and other things. note that I use the certificate x509 (the public key is from the certificate). On the receiver side, I must verify the signature of the data ( true or not). So, I use the public key of the sender for verification. But I had a problem, the public key is a string format. and i try to convert it . but unfortunately, i don't found any solution.

this the message that will be send:

data['message'] = data
data['_signature'] = self.sign_data(data)   
data['_public_key'] = str ( self.certificate.public_key())
1 Answers

You cannot convert the public key (certificate.public_key()) into string by using str, because this method will return key object.

if you need to encode the public key as PEM string, then you have to do it correctly, by serialization into PEM:

public_pem = public_key.public_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PublicFormat.SubjectPublicKeyInfo
)

Then from other side, you could load the PEM key and use it:

from cryptography.hazmat.primitives import serialization

public_key2 = serialization.load_pem_public_key(public_pem, default_backend())
Related