How to export a private key / public key into bytes with Python cryptography module?

568 Views Asked by At

I tried many combinations of parameters of rsa.RSAPrivateKey.private_bytes but none of them work:

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.serialization import Encoding, PrivateFormat, PublicFormat, NoEncryption

private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend())
pvt_bytes = private_key.private_bytes(Encoding.Raw, PrivateFormat.Raw, NoEncryption())
# ERROR
# ValueError: format is invalid with this key

public_key = private_key.public_key()
pub_bytes = public_key.public_bytes(Encoding.Raw, PublicFormat.Raw)

print(pvt_bytes, pub_bytes)

Question: how to export/import a private key / public key into a bytes form with the Python cryptography module?

The goal is to have a base64 encoded version of both like:

uFWnMdqUALp2NcvKRxE8Fw2uWDbBjnSk5wveuL3DOp7Ct4AyYKpvccMEE63ooYoj4nblafAwXikakGPbCM4amg==

0

There are 0 best solutions below