Generate PEM-Encoded PKCS#8 Format RSA Key Pair using Python

pycryptodome package

  1. Install pycryptodome package from the command line:
pip install pycryptodome
  1. Generate PEM-encoded PKCS#8 format RSA key pair:
from Crypto.PublicKey import RSA

keySize = 2048

key = RSA.generate(keySize)

privateKey = key.export_key('PEM', pkcs=8).decode('utf-8')
publicKey = key.publickey().export_key().decode('utf-8')

print(privateKey)
print(publicKey)

cryptography package

  1. Install cryptography package from the command line:
pip install cryptography
  1. Generate PEM-encoded PKCS#8 format RSA key pair:
from cryptography.hazmat.primitives import serialization as crypto_serialization
from cryptography.hazmat.primitives.asymmetric import rsa

keySize = 2048

key = rsa.generate_private_key(public_exponent=65537, key_size=keySize)

privateKey = key.private_bytes(
    crypto_serialization.Encoding.PEM,
    crypto_serialization.PrivateFormat.PKCS8,
    crypto_serialization.NoEncryption()
)
privateKey = privateKey.decode('utf-8')

publicKey = key.public_key().public_bytes(
    crypto_serialization.Encoding.PEM,
    crypto_serialization.PublicFormat.SubjectPublicKeyInfo
)
publicKey = publicKey.decode('utf-8')

print(privateKey)
print(publicKey)

Leave a Comment

Cancel reply

Your email address will not be published.