Search code examples
python-3.xcryptographyx509certificatesignaturepublic-key

How to convert a public key from string type to PEM?


I need to send a message from sender to receiver, and the message content is 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 (whether it is valid or not). So, I use the public key of the sender for verification.

But the problem is the public key is ib string format, so I tried to convert it. But unfortunately, I did't find any solution.

This is the message that will be sent:

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

Solution

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

    If you need to encode the public key as a 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())